spring学习笔记(二)spring 事件的使用

spring 中的事件java

spring事件经过订阅发布 能够解耦操做 能够同步 能够异步spring

步骤app

  • 编写事件 经过继承org.springframework.context.ApplicationEvent 来编写事件
public ApplicationEvent(Object source) {
		super(source);
		this.timestamp = System.currentTimeMillis();
	}

source 为事件传递的资源,在使用场景中 能够是数据,也能够是函数。 事件事例以下:异步

public class MySpringEvent extends ApplicationEvent {

    private boolean signal;

    /**
     * Create a new ApplicationEvent.
     *
     * @param signal  这里我传递一个信号到事件监听器中
     */
    public MySpringEvent(Boolean signal) {
        super(signal);
        this.signal=signal;
    }

    public void doSomething() {
        System.out.println("i am  an  event");
    }

    public boolean isSignal() {
        return signal;
    }
}
  • 发布事件 发布事件经过实现 事件发布接口org.springframework.context.ApplicationEventPublisher 或者 其门面接口org.springframework.context.ApplicationEventPublisherAware 推荐门面接口

相关实现以下:ide

public class MySpringEventPublisherAware implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;

    private MySpringEvent mySpringEvent;

    public MySpringEventPublisherAware(MySpringEvent mySpringEvent) {
        this.mySpringEvent = mySpringEvent;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }

    /**
     * 发送事件动做   事件的动做须要主动触发
     */
    public void refreshEvent() {
        System.out.println(">>>>>>>>>>>>>>>>>>>");
        this.applicationEventPublisher.publishEvent(mySpringEvent);
    }


}

须要特别注意的是 该发布器须要注册为spring bean 并且须要主动调用 org.springframework.context.ApplicationEventPublisher#publishEvent(ApplicationEvent event) 来触发事件函数

  • 编写监听器 经过实现 org.springframework.context.ApplicationListener<E extends ApplicationEvent> 来实现事件的监听
public class MyApplicationEventListener implements ApplicationListener<MySpringEvent> {
    @Override
    public void onApplicationEvent(MySpringEvent event) {
           event.doSomething();

            System.out.println(event.isSignal());
    }

}

经过泛型来限制监听的事件类型,该监听器一样须要注册为spring bean。测试

  • 测试用例

相关文章
相关标签/搜索