繁体   English   中英

Spring递归加载应用程序上下文

[英]Spring recursively loading application context

我想在加载应用程序上下文后调用一个方法。 我使用了ApplicationListener接口并实现了onApplicationEvent

applicationContext.xml

<beans>
    <bean id="loaderContext" class="com.util.Loader" />
    <bean id="testServiceHandler" class="com.bofa.crme.deals.rules.handler.TestServiceHandlerImpl">
</beans>



Loader.java

public class Loader implements ApplicationListener {

   public void onApplicationEvent(ApplicationEvent event) {
         ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
         TestHandlerServiceImpl test = (TestServiceHandlerImpl)context.getBean("testServiceHandler"); 
   }
}

但上面的代码是递归的。 是否可以从onApplicationEvent函数中的应用程序上下文中获取bean?

而不是在侦听器上创建新上下文,实现接口ApplicationContextAware ,将注入您的上下文。

如果您使用的是Spring 3或更高版本:

从Spring 3.0开始,ApplicationListener一般可以声明它感兴趣的事件类型。当使用Spring ApplicationContext注册时,将相应地过滤事件,只调用侦听器以匹配事件对象。

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/ApplicationListener.html#onApplicationEvent-E-

看起来如下。 另请注意,此解决方案将确保仅在此事件上执行(即启动/加载):即使您将上下文注入原始类,它也会在任何事件中执行。

public class Loader implements ApplicationListener<ContextStartedEvent> {

   public void onApplicationEvent(ContextStartedEvent event) {
         ApplicationContext context = event.getApplicationContext(); 
   }
}

看这里的例子:

http://www.tutorialspoint.com/spring/event_handling_in_spring.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM