简体   繁体   中英

Spring recursively loading application context

I want to invoke a method after the application context is loaded. I used ApplicationListener interface and implemented 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 ?

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

If you are using Spring 3 or higher:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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