1

在 Grails 中,服务默认是单例的。我可以保持这种方式并仍然从控制器创建该服务的内部类的实例吗?

//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;
         }
     }

}

在控制器“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() 
4

1 回答 1

1

您应该能够执行以下操作:

class MyTestService{

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

     def InnerTestFactory() {
        new InnerTest()
     }

}

并从您的控制器中使用它:

def m=myTestService.InnerTestFactory();
于 2015-04-17T00:07:20.857 回答