前言
记录一下java中监听器相关资料
一、监听器是什么?
用来监听其他对象的变化
二、类型
1.Request
1.1. ServletRequestListener
监听Request的创建和销毁
/**
requestInitialized 表示监听requst初始化
requestDestroyed表示监听request销毁
*/
public interface ServletRequestListener extends EventListener {
default void requestDestroyed( ServletRequestEvent sre) {
}
default void requestInitialized(ServletRequestEvent sre) {
}
1.2.ServletRequestAttributeListener
Request的属性进行监听
2.Session
2.1. HttpSessionListener
监听HttpSession的创建跟销毁
public interface HttpSessionListener extends EventListener {
//sessionCreated表示监听session创建,当有session创建,该方法就会执行
default void sessionCreated( HttpSessionEvent se) {
}
//sessionDestroyed表示监听session销毁,当有session销毁,该方法就会执行
default void sessionDestroyed(HttpSessionEvent se) {
}
}
2.2.HttpSessionAttributeListener
监听session新增属性、移除属性和属性值被替换时
3.ServletContext
3.1. ServletContextListener
ServletContext的创建和销毁
3.2.ServletContextAttributeListener
ServletContext中属性的新增、移除和属性值的替换
4.ApplicationListener
ApplicationContext事件机制是观察者设计模式的实现,通过ApplicationEvent类和ApplicationListener接口,可以实现ApplicationContext事件处理。
如果容器中有一个ApplicationListener Bean,每当ApplicationContext发布ApplicationEvent时,ApplicationListener Bean将自动被触发。这种事件机制都必须需要程序显示的触发。
其中spring有一些内置的事件,当完成某种操作时会发出某些事件动作。比如监听ContextRefreshedEvent事件,当所有的bean都初始化完成并被成功装载后会触发该事件,实现ApplicationListener接口可以收到监听动作,然后可以写自己的逻辑。
同样事件可以自定义、监听也可以自定义,完全根据自己的业务逻辑来处理。
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}