Spring 使用介绍(十一)—— Spring事件

一、简介

spring事件是观察者设计模式的实现,主要有三个元素:

  • 事件  spring事件由ApplicationEvent定义
  • 发布者  由ApplicationEventPublisher定义,而ApplicationContext继承自ApplicationEventPublisher
  • 监听者  由ApplicationListener定义

简单示例:

自定义事件

public class TestEvent extends ApplicationEvent {
    
    private String message;

    public TestEvent(Object source) {
        this(source, "default message");
    }
    
    public TestEvent(Object source, String msg) {
        super(source);
        this.message = msg;
    }

    public String getMessage() {
        return message;
    }
}

监听者

@Component
public class TestListener implements ApplicationListener<ApplicationEvent>  {
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof TestEvent) {
        System.out.println(((TestEvent)event).getMessage());
        }    
    }
}

XML配置

<context:component-scan base-package="cn.matt.event"/>  

测试

public class EventTest {
    @Test
    public void testCustomEvent() {
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-context.xml");
        context.publishEvent(new TestEvent("", "hello matt"));
    }
}

补充:

定义监听者时,可通过泛型指定监听事件类型,因此,上例监听者可定义如下:

@Component
public class TestListener implements ApplicationListener<TestEvent> {
    @Override
    public void onApplicationEvent(TestEvent event) {
        System.out.println(((TestEvent) event).getMessage());
    }
}

二、spring容器事件

扫描二维码关注公众号,回复: 871767 查看本文章

spring为容器启动各阶段定义了相关事件,实现如图:

事件说明:

  • ContextStartedEvent:ApplicationContext启动后触发的事件(调用start方法)
  • ContextStoppedEvent:ApplicationContext停止后触发的事件(调用stop方法)
  • ContextRefreshedEvent:ApplicationContext初始化或刷新完成后触发的事件(容器初始化(如bean的实例化、依赖注入)完成后调用)
  • ContextClosedEvent:ApplicationContext关闭后触发的事件(如web容器关闭时自动会触发spring容器的关闭,如果是普通java应用,需要调用ctx.registerShutdownHook()注册虚拟机关闭时的钩子才行)

使用示例

@Component
public class ApplicationStartUpListener implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {    
        System.out.println("spring context inited");    
    }
}

猜你喜欢

转载自www.cnblogs.com/MattCheng/p/9046980.html