Groovy/src中的Grails2.x服务注入

Groovy/src中的Grails2.x服务注入,grails,grails-2.0,Grails,Grails 2.0,我想在Groovy/src类中注入我的服务。normaln依赖项注入不起作用: ... def myService ... 我可以使用这个(它可以工作): 但是ApplicationHolder已被弃用。有没有更好的解决办法 感谢您的建议您可以通过在grails app/conf/spring/resources.groovy中配置新的(或覆盖现有的)bean来轻松注册它们: // src/groovy/com/example/MyClass.groovy class MyClass {

我想在Groovy/src类中注入我的服务。normaln依赖项注入不起作用:

...
def myService
...
我可以使用这个(它可以工作):

但是ApplicationHolder已被弃用。有没有更好的解决办法


感谢您的建议

您可以通过在
grails app/conf/spring/resources.groovy中配置新的(或覆盖现有的)bean来轻松注册它们:

// src/groovy/com/example/MyClass.groovy
class MyClass {
    def myService
    ...
}

// resources.groovy
beans = {
    myclass(com.example.MyClass) {
        myService = ref('myService')
    }
}
// src/groovy/com/example/MyClass.groovy
class MyClass {
    def myService
    ...
}

// resources.groovy
beans = {
    myclass(com.example.MyClass) {
        myService = ref('myService')
    }
}

您还可以检查这个关于

的问题,检查以下Grails常见问题以从src/groovy中的源代码访问应用程序上下文-:如何从src/groovy中的源代码访问应用程序上下文

没有与ApplicationHolder等效的ApplicationContextHolder类。要从src/Groovy中的Groovy类访问名为EmailService的服务类,请使用以下命令访问Springbean:

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes as GA
def ctx = SCH.servletContext.getAttribute(GA.APPLICATION_CONTEXT)
def emailService = ctx.emailService

ApplicationHolder的更换可以是,也可以在静态范围内使用:

import grails.util.Holders
...

def myService = Holders.grailsApplication.mainContext.getBean 'myService'

您可以从
资源中执行此操作。groovy

// src/groovy/com/example/MyClass.groovy
class MyClass {
    def myService
    ...
}

// resources.groovy
beans = {
    myclass(com.example.MyClass) {
        myService = ref('myService')
    }
}
// src/groovy/com/example/MyClass.groovy
class MyClass {
    def myService
    ...
}

// resources.groovy
beans = {
    myclass(com.example.MyClass) {
        myService = ref('myService')
    }
}
或者仅使用自动连线的anotation:

// src/groovy/com/example/MyClass.groovy

import org.springframework.beans.factory.annotation.Autowired

class MyClass {
    @Autowired 
    def myService
    ...
}

// resources.groovy
beans = {
    myclass(com.example.MyClass) {}
}

如何使用这个“src类”?在哪里以及如何实例化它?我在其他Groovy类中使用它(在那里实例化)。有一个facade groovy类,由触发所有这些过程的服务使用。我不想将使用过的服务作为参数传递,以免传递太多的参数……现在我发现这对我不起作用。我不能像这样绑定resources.groovy中的服务或其他属性:`import com.path.to.residentatplacebeans={residentAtPlaceBean(ResidentAtPlace){someProperty=45 placeService=ref('placeService')grailsApplication=ref('grailsApplication')}“在我的住处,一切都是空的?我使用的是Grail2.0.3同样的情况也发生在我身上,知道为什么吗?虽然这将允许您访问服务中的方法,但它将破坏服务的事务性。摘自:警告:依赖项注入是声明性事务工作的唯一方式。如果使用new BookService()@ubiquibacon等新运营商,您将无法获得事务性服务-是的,但“def emailService=ctx.emailService”将是事务性服务。很抱歉,这样访问服务有什么问题?我认为这不符合“依赖注入”的条件。不过我得做些测试来证实这一点。调查的结果是什么?