Grails:在Bootstrap代码的关闭中访问spring beans? [英] Grails: Accessing spring beans in the destory closure of Bootstrap code?

查看:98
本文介绍了Grails:在Bootstrap代码的关闭中访问spring beans?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找在我的grails项目的Bootstrap.groovy中的destroy关闭中访问一个bean。

我似乎无法访问servletContext ...?

解决方案

您可以使用该块代码从各处获得对applicationContext的引用(包括BootStrap的销毁关闭):

  def ctx = org.codehaus.groovy.grails.web.context.ServletContextHolder.servletContext.getAttribute(org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes.APPLICATION_CONTEXT); 

获取对bean的引用就像 ctx.beanName <

这是一个小的util类(用Java编写),可以简化这个任务:

  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)

干杯,Sigi


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?

I seem to have no access to servletContext...?

解决方案

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

Getting a reference to a bean is as easy as ctx.beanName.

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

}

and an example:

def bean = SpringUtil.getBean("beanName")

Cheers, Sigi

这篇关于Grails:在Bootstrap代码的关闭中访问spring beans?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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