Tomcat,spring初始化时加载自定义监听器方法
Tomcat初始化时加载自定义监听器方法:
1.创建一个监听器MyListener继承ServletContextListener
//@Component //监听器是web层的组件,它是tomcat实例化的,不是Spring实例化的。不能放到Spring中
public class MyListener implements ServletContextListener {
private UserService userService = null;//UserService中的相关逻辑
@Override
public void contextDestroyed(ServletContextEvent event) {
}
@Override
public void contextInitialized(ServletContextEvent event) {
项目在启动时,把Spring配置文件通过Spring的监听器加载,存储到ServletContext中,我们只要在ServletContext中获取即可。
ApplicationContext context = (ApplicationContext) event.getServletContext()
.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
userService = (UserService) context.getBean("UserService");
System.out.println(userService);
}
} 、
2.并在web.xml中配置该监听器:
这是tomcat加载spring容器的配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:beans.xml</param-value>
</context-param>
而加载我们自定义监听器也需要配置在web.xml中
<listener>
<listener-class>com.listener.MyListener</listener-class>
</listener>
2.加载spring监听器方法
@Component//由加载spring容器时实例化该监听器
public class CreateDefaultAdminListener implements
ApplicationListener<ContextRefreshedEvent> {
@Autowired
private LoginService loginService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(!loginService.hasAdmin()){
loginService.createDefaultAdmin();
}
}
}、