Search code examples
javaspringspring-ioc

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 ?


Solution

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