我爱编程

Spring中的事件机制

2018-03-31  本文已影响0人  柚子过来

Spring中通过事件与对应的监听器可以完成很多操作,比如关于context容器的的事件有如下4个:

ContextStartedEvent

明确调用ConfigurableApplicationContext.start()才会触发. 在spring boot中可以使用如下方法触发

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args).start();
    }
}
ContextRefreshedEvent:

当ApplicationContext初始化结束或者刷新的时候触发. 这里的初始化结束是指所有的bean已经加载完毕, post-processor bean被激活, 单例bean被初始化, 同时ApplicationContext对象可以被使用了.
也可以明确调用refresh()方法触发. 但是要注意, 并不是所有的ApplicationContext实例都支持hot refresh的, 比如GenericApplicationContext是不支持hot refresh的, 所以Spring boot中如果直接调用

SpringApplication.run(DemoApplication.class, args).refresh();

就会报
Exception in thread "main" java.lang.IllegalStateException: GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once
错误, 因为Spring boot中的ApplicationContext实例是AnnotationConfigEmbeddedWebApplicationContext, 是继承于GenericApplicationContext的. 但是XmlWebApplicationContext就是支持hot refresh

ContextStoppedEvent

可以通过调用ConfigurableApplicationContext.stop()触发. 当ApplicationContext调用了stop()之后, 可以重新调用start()启动context.

ContextClosedEvent

当ApplicationContextclose时触发, 可以手动调用close()方法或者直接退出应用来触发.


除了这些已有的事件,我们也可以通过继承ApplicationEvent类来自己定义事件,再使用publishEvent方法来发布事件,这样就可以使用@EventListener定义监听器来进行相关处理了。下面举一个例子:

先定义一个Event事件:

public class MyEvent extends ApplicationEvent {
private String index;
//构造器必须要有Object参数并调用父构造器,这个source就是生成该event的那个对象
MyEvent(Object source,String s) {
    super(source);
    this.index = s;
}

public String getIndex() {
    return index;
}
}

然后我们通过ApplicationContext发布这个事件并添加监听器:

@Configuration
public class Config {

@Autowired
private ApplicationContext context;

//填加一个监听器监听我们的事件,监听到就做相关操作
@EventListener
public void onApplicationEvent(MyEvent event){
    System.out.println("Get My Event !!!!!!");
    System.out.println(event.getIndex());
}
//在容器初始化的时候发布我们定义的事件
@EventListener({EmbeddedServletContainerInitializedEvent.class})
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
     //发布,其实就是将该event放到一个Set<ApplicationEvent>里
    this.context.publishEvent(new MyEvent(this,"hello jWang"));
}
}

这样我们启动应用,会发现控制台打印了:

Get My Event !!!!!!
hello jWang

如果不使用@EventListener注解(Spring 4.2以后可以用),也可以单独的定义一个监听器类:

@Component
public class Listener implements ApplicationListener<MyEvent> {

@Override
public void onApplicationEvent(MyEvent event) {
    System.out.println("Get My Event Via Listener!!!!!!");
    System.out.println(event.getIndex());
}
}

说了事件机制的使用方法后,再说说它的原理.
可以看出事件机制就是一个Event被发布的时候,Listener会执行相应的操作,这很像一个观察者的设计模式。

查看源码可以发现Listener注册后会被放入一个集合中:

 public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet();

然后我们看发布事件的时候发生了什么:

    protected void publishEvent(Object event, ResolvableType eventType) {
    ... ...

    if (this.earlyApplicationEvents != null) {
        this.earlyApplicationEvents.add(applicationEvent);
    } else {
      
       //这一句进去看看
        this.getApplicationEventMulticaster().multicastEvent((ApplicationEvent)applicationEvent, eventType);
    }

    if (this.parent != null) {
        if (this.parent instanceof AbstractApplicationContext) {
            ((AbstractApplicationContext)this.parent).publishEvent(event, eventType);
        } else {
            this.parent.publishEvent(event);
        }
    }
}

事件机制的逻辑核心在类SimpleApplicationEventMulticaster中,那进入multicastEvent方法:

public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
    ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);

    //获取了该事件的Listener集合
    Iterator var4 = this.getApplicationListeners(event, type).iterator();

     //对每个Listener进行处理
    while(var4.hasNext()) {
        final ApplicationListener<?> listener = (ApplicationListener)var4.next();
        Executor executor = this.getTaskExecutor();
        if (executor != null) {
            executor.execute(new Runnable() {
                public void run() {

                    //invokeListener里面就是调用该Listener的onApplicationEvent方法
                    SimpleApplicationEventMulticaster.this.invokeListener(listener, event);
                }
            });
        } else {
            this.invokeListener(listener, event);
        }
    }
}

可以看出事件机制中的观察者模式的实现方式是事件发生时主动推送“通知”观察者调用其处理逻辑(还有一种是观察者自己去轮询查有没有新事件)。

上一篇下一篇

猜你喜欢

热点阅读