【问题标题】:Grails: Accessing spring beans in the destory closure of Bootstrap code?Grails:在 Bootstrap 代码的 destory 闭包中访问 spring bean?
【发布时间】:2010-10-09 03:45:24
【问题描述】:

我希望在我的 grails 项目的 Bootstrap.groovy 中的销毁闭包中访问一个 bean。关于如何实现这一点的任何想法?

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

【问题讨论】:

    标签: spring grails bootstrapping


    【解决方案1】:

    您可以使用该代码块从任何地方(包括 BootStrap 的销毁闭包)获取对 applicationContext 的引用:

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

    干杯,西吉

    【讨论】:

      【解决方案2】:

      我知道我在这里都迟到了,但是因为我是通过 Google 找到的...

      您的 BootStrap 类按名称注入 Spring bean,就像所有服务和控制器等一样。如果你想要一个 bean,只需按名称定义它,它就会出现。否则,只需 def grailsApplication 并转到 grailsApplication.mainContext.getBean 等。

      【讨论】:

        【解决方案3】:

        嗯,我找不到任何人的例子,甚至在 Bootstrap 中使用破坏块闭包。来自文档:

        不保证会调用 {{destroy}},除非 应用程序正常退出(例如通过使用应用程序 服务器的关闭命令)所以不要过分依赖它

        作为一种猜测,我不得不说 servletContext 在执行 Bootstrap 的 {{destroy}} 闭包之前已经被销毁,因此您尝试访问的 bean 已经消失了。谁能确认一下?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-07-07
          • 2011-07-27
          • 1970-01-01
          • 2016-11-30
          • 1970-01-01
          • 1970-01-01
          • 2018-04-23
          • 2012-04-04
          相关资源
          最近更新 更多