简体   繁体   English

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

[英]Spring recursively loading application context

I want to invoke a method after the application context is loaded. 我想在加载应用程序上下文后调用一个方法。 I used ApplicationListener interface and implemented onApplicationEvent . 我使用了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"); 
   }
}

But the above code goes recursive. 但上面的代码是递归的。 Is it possible to get a bean from application context inside onApplicationEvent function ? 是否可以从onApplicationEvent函数中的应用程序上下文中获取bean?

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

If you are using Spring 3 or higher: 如果您使用的是Spring 3或更高版本:

As of Spring 3.0, an ApplicationListener can generically declare the event type that it is interested in. When registered with a Spring ApplicationContext, events will be filtered accordingly, with the listener getting invoked for matching event objects only. 从Spring 3.0开始,ApplicationListener一般可以声明它感兴趣的事件类型。当使用Spring ApplicationContext注册时,将相应地过滤事件,只调用侦听器以匹配事件对象。

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

which would look like the following. 看起来如下。 Note also that this solution will ensure it is only executed on this event (ie start/load): it looks to me like even if you inject the context to your original class it would be executed for any event. 另请注意,此解决方案将确保仅在此事件上执行(即启动/加载):即使您将上下文注入原始类,它也会在任何事件中执行。

public class Loader implements ApplicationListener<ContextStartedEvent> {

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

See examples here: 看这里的例子:

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

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

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