Grails:在 Bootstrap 代码的 destory 闭包中访问 spring bean? [英] Grails: Accessing spring beans in the destory closure of Bootstrap code?
问题描述
我希望在我的 grails 项目的 Bootstrap.groovy 中的 destroy 闭包中访问一个 bean.关于如何实现这一目标的任何想法?
I'm looking to access a bean in my destroy closure in the Bootstrap.groovy of my grails project. Any ideas on how to achieve this?
我似乎无法访问 servletContext...?
I seem to have no access to servletContext...?
推荐答案
您可以使用该代码块从任何地方(包括 BootStrap 的 destroy 闭包)获取对 applicationContext 的引用:
You can obtain a a reference to the applicationContext from everywhere (including the destroy closure of BootStrap) using that chunk of code:
def ctx = org.codehaus.groovy.grails.web.context.ServletContextHolder.servletContext.getAttribute(org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes.APPLICATION_CONTEXT);
获取对 bean 的引用就像 ctx.beanName
一样简单.
Getting a reference to a bean is as easy as ctx.beanName
.
这是一个可以简化此任务的小型 util 类(用 Java 编写):
Here is a small util class (written in Java) that can simplify this task:
import org.springframework.context.ApplicationContext;
import org.codehaus.groovy.grails.web.context.ServletContextHolder;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
public class SpringUtil {
public static ApplicationContext getCtx() {
return getApplicationContext();
}
public static ApplicationContext getApplicationContext() {
return (ApplicationContext) ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName) {
return (T) getApplicationContext().getBean(beanName);
}
}
和一个例子:
def bean = SpringUtil.getBean("beanName")
干杯,西吉
这篇关于Grails:在 Bootstrap 代码的 destory 闭包中访问 spring bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!