Reputation: 211
I am trying to autowiring my bean inside contextInitialized() method of my custom Context Listener class, but it is not working.
public class CustomContextListener extends ContextLoaderListener {
@Autowired
private MyBeanClass bean;
@Override
public void contextInitialized(javax.servlet.ServletContextEvent event) {
super.contextInitialized(event);
//call to my method.
bean.mymethod();
}
But here it is not getting autowired, i am getting null object for MyBeanClass reference. How to autowire a class at the time of tomcat startup. Please provide me alternate places where i can execute some code using autowiring at the time of server startup (here tomcat).
Upvotes: 2
Views: 1721
Reputation: 84
I would suggest to use the WebApplicationContext method to find the bean and then invoke.
WebApplicationContext servletContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
bean = (MyBeanClass) servletContext.getBean("myBeanClass");
bean.yourMethod();
More systematic to use... :)
Upvotes: 1