ApplicationListener 和@EventListener 注解实现事件监听
4,995 total views, 12 views today
对于 Spring 容器的一些事件,可以监听并且触发相应的方法。通常的方法有 2 种,ApplicationListener 接口和@EventListener 注解。
ApplicationListener 接口
ApplicationListener 接口的定义如下:
1 2 3 4 5 6 7 8 |
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener { /** * Handle an application event. * @param event the event to respond to */ void onApplicationEvent(E event); } |
它是一个泛型接口,泛型的类型必须是 ApplicationEvent 及其子类,只要实现了这个接口,那么当容器有相应的事件触发时,就能触发 onApplicationEvent 方法。ApplicationEvent 类的子类有很多,Spring 框架自带的如下几个。

使用方法很简单,就是实现一个 ApplicationListener 接口,并且将加入到容器中就行。
1 2 3 4 5 6 7 8 |
@Component public class MyApplicationListener implements ApplicationListener<ApplicationEvent> { @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println("事件触发:"+event.getClass().getName()); } } |
当 main 方法运行的时候:
1 2 3 4 |
public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(Config.class); applicationContext.close(); } |
结果如下:
1 2 |
事件触发:org.springframework.context.event.ContextRefreshedEvent 事件触发:org.springframework.context.event.ContextClosedEvent |
@EventListener 注解
除了通过实现接口,还可以使用@EventListener 注解,实现对任意的方法都能监听事件。
1 2 3 4 5 6 7 8 |
@Configuration @ComponentScan(value = "com.learn") public class Config { @EventListener(classes={ApplicationEvent.class}) public void listen(ApplicationEvent event){ System.out.println("事件触发:"+event.getClass().getName()); } } |
在任意方法上标注@EventListener 注解,指定 classes,即需要处理的事件类型,一般就是 ApplicationEven 及其子类,可以设置多项。
结果如下:
1 2 |
事件触发:org.springframework.context.event.ContextRefreshedEvent 事件触发:org.springframework.context.event.ContextClosedEvent |
原创文章,转载请注明出处!http://www.javathings.top/applicationlistener和eventlistener注解实现事件监听/