Spring 事件(1)- 内置事件

Spring中的事件是一个ApplicationEvent类的子类,由实现ApplicationEventPublisherAware接口的类发送,实现ApplicationListener接口的类监听。

ApplicationContext 事件

Spring中已经定义了一组内置事件,这些事件由ApplicationContext容器发出。

例如,ContextStartedEventApplicationContext启动时发送,ContextStoppedEventApplicationContext停止时发送。

实现ApplicationListener的类可以监听事件。

Spring的事件是同步的(单线程的),会被阻塞。

监听ApplicationContext事件

要监听ApplicationContext事件,监听类应该实现ApplicationListener接口并重写onApplicationEvent()方法。

ContextStartEventHandler.java

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

public class ContextStartEventHandler implements ApplicationListener<ContextStartedEvent>{

	@Override
	public void onApplicationEvent(ContextStartedEvent event) {
		System.out.println("ApplicationContext 启动... ");
	}
}

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
  public static void main(String[] args) {
    // ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    // ((ConfigurableApplicationContext) context).start();
    
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    // fire the start event.
    context.start();
    
    // ...
    
  }
}

在XML配置文件中,将该类为声明为Bean,以便Spring容器加载该Bean,并向其传送事件。

<bean id="contextStartEventHandler" class="ContextStartEventHandler"></bean>
posted @ 2019-06-07 10:22  吴吃辣  阅读(461)  评论(0编辑  收藏  举报