Grails 2.x service injection in Groovy/src

南楼画角 提交于 2019-11-27 22:16:47

问题


I'd like to inject my service in Groovy/src class. The normaln dependency injection doesn't work:

...
def myService
...

I'm able to use this (it works):

def appCtx = ApplicationHolder.application.getMainContext()
def myService = appCtx.getBean("myService");

but the ApplicationHolder is deprecated. Is there any better solution?

Thanks for any suggestion


回答1:


Check following Grails FAQ to get access to the application context from sources in src/groovy - http://grails.org/FAQ#Q: How do I get access to the application context from sources in src/groovy?

There is no ApplicationContextHolder class equivalent to ApplicationHolder. To access to a service class called EmailService from a Groovy class in src/groovy, access the Spring bean using:

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



回答2:


The replacement of ApplicationHolder can be Holders, you can also use it in static scope:

import grails.util.Holders
...

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



回答3:


You can easily register new (or override existing) beans by configuring them in grails-app/conf/spring/resources.groovy:

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

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

Also you can check this question about How to access Grails configuration in Grails 2.0?




回答4:


Yo can do it from the resources.groovy:

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

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

or just using the autowired 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) {}
}


来源:https://stackoverflow.com/questions/10640480/grails-2-x-service-injection-in-groovy-src

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!