永远学不完的JAVA

ApplicationListener

2019-08-29  本文已影响0人  超速蜗牛1984

大致步骤

 * ApplicationListener:监听容器中发布的事件,事件驱动模型开发
 *   public interface ApplicationListener<E extends ApplicationEvent> extends EventListener
 *   步骤:
 *   1、写一个监听器来监听某个事件(ApplicationEvent及其子类)
 *   2、把监听器放入容器中
 *   3、只有容器中有响应类型的事件发布,我们就能监听到这个事件
 *         ContextRefreshedEvent:容器刷新完成
 *         ContextClosedEvent:关闭容器发布这个事件
 *   4、自己来发布一个事件

配置类

@ComponentScan("com.dwd.snail.testspring.test.ext")
@Configuration
public class ExtConfig {

}

实现ApplicationListener接口并注册到容器中

@Component
public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
    //当容器中发布此事件后,方法会得到触发
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        System.out.println("收到事件...");
        System.out.println(event);

    }
}

测试类

public class IocTest_ext {

    @Test
    public void test01(){
        AnnotationConfigApplicationContext applicationContext=new AnnotationConfigApplicationContext(ExtConfig.class);

        applicationContext.publishEvent(new ApplicationEvent(new String("发布事件snail")) {
        });
        applicationContext.close();


    }

测试结果

收到事件...
org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@62043840: startup date [Thu Aug 29 15:13:23 CST 2019]; root of context hierarchy]
收到事件...
com.dwd.snail.testspring.IocTest_ext$1[source=发布事件snail]
15:13:25.235 [main] INFO org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@62043840: startup date [Thu Aug 29 15:13:23 CST 2019]; root of context hierarchy
收到事件...
org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@62043840: startup date [Thu Aug 29 15:13:23 CST 2019]; root of context hierarchy]
上一篇下一篇

猜你喜欢

热点阅读