观察者模式:ServletContextListener

ServletContextListener:是对javax.servlet.ServletContext(application)的监听。
ApplicationListener:是对Spring的ApplicationContext的监听。
HttpSessionListener:是对javax.servlet.http.HttpSession(session)的监听。
HttpSessionAttributeListener接口:对session的属性监听。
基于ServletContextListener的监听器要比基于ApplicationListener的监听器先执行。因为前者是Tomcat/Jetty容器启动后就执行,后者需要Spring应用初始化完成后才执行。

ServletContextListener

ServletContextAttributeListener
ServletRequestListener

每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。

public interface ServletContextListener extends EventListener {
	public void contextInitialized(ServletContextEvent sce);
	public void contextDestroyed(ServletContextEvent sce);
}

如果是普通Spring应用,则还需要配置web.xml

<listener>
    <listener-class>com.my.listener.TestListener</listener-class>
</listener>

如果是SpringBoot应用,则使用@WebListener注解。
在Springboot web 应用启动代码中添加@ServletComponentScan注解。
添加@ServletComponentScan注解后Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
如果@Autowired注入bean,可能是null。

@WebListener
public class MyServletContextListener implements ServletContextListener{
	public void contextInitialized(ServletContextEvent sce){
		//这样的话,@Autowired注入bean就可以使用了
		WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext())
				.getAutowireCapableBeanFactory().autowireBean(this);
		System.out.println("dao++++"+dao.count());
	}
	public void contextDestroyed(ServletContextEvent sce);
	@Autowired
	private MyDao dao;
}

ApplicationListener

在普通Spring环境中,基于ApplicationListener的监听器的onApplicationEvent方法可能会被执行多次。
在web 项目中(spring mvc),系统会存在两个容器,一个是root application context,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    if(event.getApplicationContext().getParent() == null){
    	//需要执行的逻辑代码
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值