【问题标题】:Autowiring inside contextInitialized method of Context Listener在 Context Listener 的 contextInitialized 方法中自动装配
【发布时间】:2012-03-16 13:27:38
【问题描述】:

我正在尝试在我的自定义 Context Listener 类的 contextInitialized() 方法中自动装配我的 bean,但它不起作用。

public class CustomContextListener extends ContextLoaderListener {
    @Autowired
    private MyBeanClass bean;

    @Override
    public void contextInitialized(javax.servlet.ServletContextEvent event) {
          super.contextInitialized(event);
          //call to my method.
          bean.mymethod();
}

但是这里它没有自动装配,我得到了 MyBeanClass 引用的空对象。 如何在 tomcat 启动时自动装配一个类。 请提供我可以在服务器启动时使用自动装配执行一些代码的备用位置(此处为 tomcat)。

【问题讨论】:

  • ContextLoaderListener 本身并不由 Spring 管理,它用于创建应用程序上下文。您不能在其中使用自动装配。你需要解释你想要达到的目标。
  • 我想在启动我的应用程序时安排工作

标签: spring-mvc tomcat autowired bootstrapping


【解决方案1】:

我建议使用 WebApplicationContext 方法找到 bean 然后调用。

WebApplicationContext servletContext =  WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());

bean = (MyBeanClass) servletContext.getBean("myBeanClass");
bean.yourMethod();

更系统的使用... :)

【讨论】:

  • 此代码工作正常,正在使用此代码,但此处未更新。这是公认的答案。
猜你喜欢
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 1970-01-01
  • 2015-07-31
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多