1

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() 
Burt Beckwith
  • 75,342
  • 5
  • 143
  • 156
user2782001
  • 3,380
  • 3
  • 22
  • 41
  • yep the errors it produces are in the code comments. Is the cannot be cast error due to the singleton nature of the service? – user2782001 Apr 16 '15 at 23:48

1 Answers1

1

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();
M. Adam Kendall
  • 1,202
  • 9
  • 8