Grails创建内部服务类的实例

时间:2015-04-16 23:46:18

标签: grails grails-controller grails-services

在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() 

1 个答案:

答案 0 :(得分: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();