grailsgrails-controllergrails-services

Grails create instance of inner class of service


In Grails, services are singletons by default. Can I keep it that way and still create an instance of an inner class of that service from a controller?

//by default grails makes MyTestService a singlton
class MyTestService{

     public class InnerTest{
          String msg;
          def addMsg(String str){
               this.msg=str;
          }
          def printMsg(){
             println this.msg;
         }
     }

}

In controller "MyController"...

def m=myTestService.getInstance().new InnerTest();
//produces " MyTestService.InnerTest cannot be cast to MyTestService.InnerTest"

 def m=myTestService.new InnerTest();
//No signature of method:MyController.InnerTest() 

Solution

  • You should be able to do something like:

    class MyTestService{
    
         public class InnerTest{
              String msg;
              def addMsg(String str){
                   this.msg=str;
              }
              def printMsg(){
                 println this.msg;
             }
         }
    
         def InnerTestFactory() {
            new InnerTest()
         }
    
    }
    

    And use it from your controller:

    def m=myTestService.InnerTestFactory();