Spring recursive loading of application context
I want to call the method after loading the application context. I used the interface ApplicationListener
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 becomes recursive. Is it possible to get a bean from an application context inside a function onApplicationEvent
? please help me.
source to share
Instead of creating a new context on the listener, implement the ApplicationContextAware interface , your context will be injected.
source to share
If you are using Spring 3 or higher:
As with Spring 3.0, the ApplicationListener can generally declare the type of event it is interested in. When registering with SpringApplicationContext, events will be filtered accordingly, and a listener called only to match event objects.
which will look like this. Also note that this solution ensures that it only runs on that event (like start / load): it looks the same as if you injected the context into the original class, it will 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
source to share