Groovy/src 中的 Grails 2.x 服务注入 [英] Grails 2.x service injection in Groovy/src

查看:10
本文介绍了Groovy/src 中的 Grails 2.x 服务注入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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");

但不推荐使用 ApplicationHolder.有没有更好的解决办法?

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

感谢您的建议

推荐答案

检查以下 Grails FAQ 以从 src/groovy 中的源访问应用程序上下文 - http://grails.org/FAQ#Q:如何从 src/groovy 中的源访问应用程序上下文?

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?

没有等效于 ApplicationHolder 的 ApplicationContextHolder 类.要从 src/groovy 中的 Groovy 类访问名为 EmailService 的服务类,请使用以下命令访问 Spring bean:

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

这篇关于Groovy/src 中的 Grails 2.x 服务注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆