Spring recursively loading application context

977 Views Asked by At

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 ?

2

There are 2 best solutions below

0
On BEST ANSWER

Instead of creating a new context on the listener, implement the interface ApplicationContextAware, your context will be injected.

0
On

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 (i.e. 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