Listsner是由Tomcat管理的,Tomcat无法把SpringIOC容器的Bean注入到Listsner,而注入Bean的工作是由Spring负责的。那么解决这个问题呢?从servletContext中拿到webApplicationContext,然后调用webApplicationContext.getBean("beanName")
public class MessegeTaskListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
//获取spring容器
WebApplicationContext con= WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext());
// 获取springBean
MessegeTimerTask messegeTimerTask=con.getBean(MessegeTimerTask.class);
messegeTimerTask.begin();
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
end
so,spring IOC bean容器虽然牛逼,但是在web项目里,servlet(tomcat)容器还是爸爸,一些特殊情况还是要找爸爸
注:
spring 容器也是通过listener加载进tomcat容器的,普通listener用不了springBean 不是因为springBean没加载(是否加载看listener配置顺序),而是不在一个容器级别上