Spring ApplicationListener使用方法及问题

1 自定义监听器和spring监听器

web应用中自定义监听器需要放在spring监听器的后面。因为只有spring监听器初始化spring容器后,我们才可以在自定义监听器中获得spring容器相关东西。否则我们自定义监听器启动了,但是无法获得spring相关东西,那么这个自定义监听器的作用意义也就不大了。

附:spring监听器 org.springframework.web.context.ContextLoaderListener,项目启动时加载spring的配置文件,创建spring工厂 。ContextLoaderListener监听器的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。因为它实现了ServletContextListener这个接口,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。

2 servlet API中的监听器

图1 来自:Servlet JSP深入详解 基于Tomcat的Web开发



图2 来自Tomcat与Java Web开发技术详解


部署描述符的内容加载顺序:web.xml 的加载顺序是:context-param -> listener -> filter -> servlet ,而同个类型之间的实际程序调用的时候的顺序是根据对应的 mapping 的顺序进行调用的

Spring框架的ApplicationListener是一个接口,用于监听Spring的上下文事件。它可以用于在Spring容器启动和关闭时执行一些特定的任务。下面是使用ApplicationListener的一些步骤: 1. 创建一个实现ApplicationListener接口的类,并实现onApplicationEvent()方法。该方法会在Spring上下文中发生事件时被触发。 2. 在Spring配置文件中注册这个监听器。可以通过添加<context:component-scan>和@Component注解来实现自动扫描,或者通过手动声明一个<bean>标签来注册。 3. 如果需要监听多个事件,可以在onApplicationEvent()方法中根据事件类型进行判断,然后执行相应的操作。 下面是一个简单的例子,演示了如何使用ApplicationListener监听Spring上下文的启动和关闭事件: ```java import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; public class MyListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent) { // Spring容器启动事件 System.out.println("Spring容器启动了!"); } else if (event instanceof ContextClosedEvent) { // Spring容器关闭事件 System.out.println("Spring容器关闭了!"); } } } ``` 在Spring配置文件中注册这个监听器: ```xml <bean id="myListener" class="com.example.MyListener"/> ``` 这样,当Spring容器启动或关闭时,就会调用MyListener类的onApplicationEvent()方法,并输出相应的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值