这篇文章主要是讲解spring的事务发布机制,也顺带讲一些ApplicationContest容器启动过程。Spring事件发布机制是基于观察者模式的。其实现类图如下:
如上图所示,抽象类AbstractApplicationContext含义一个ApplicationEventMulticaster类型属性,也就是说,每一个applicationContext容器都含有一个ApplicationEventMulticaster类型属性。从图可以看出,ApplicationEventMulticaster接口的作用是管理listener和发布事件,包含了增加和删除listener的功能。当发布事件时依赖于ApplicationEvent接口,当管理listener时依赖于ApplicationListener接口。这就是整个spring监听机制的实现类图。
如何在spring框架中使用监听机制
- 定义事件
首先需要定义事件,通过实现ApplicationEvent接口来定义事件,在事件中需要包含一些事件的信息。如下为自定义的订单事件:
商品订单事件:
public class OrderEvent extends ApplicationEvent {
//货物
private String goods;
//价格
private int price;
//订单状态
private int state;
//构造器
public OrderEvent(Object source, String goods, int price, int state){
super(source);
this.goods = goods;
this.price = price;
this.state = state;
}
public String getGoods() {
return goods;
}
public void setGoods(String goods) {
this.goods = goods;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
}
购买电影票事件
public class TicketEvent extends ApplicationEvent {
//票价
private int price;
//主题
private String topic;
public TicketEvent(Object source, int price, String topic){
super(source);
this.price = price;
this.topic = topic;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
}
- 定义监听
然后通过实现ApplicationListener接口来自定义监听,在监听中需要对事件进行处理
商品事件监听器:
public class OrderListener implements ApplicationListener<OrderEvent> {
public void onApplicationEvent(OrderEvent event) {
System.out.println("创建一个订单");
System.out.println("商品名:" + event.getGoods());
System.out.println("价格:" + event.getPrice());
System.out.println("订单状态:" + event.getState());
}
}
购买电影票事件监听器:
public class TicketListener implements ApplicationListener<TicketEvent> {
public void onApplicationEvent(TicketEvent event) {
System.out.println("购买一张电影票");
System.out.println("票价:" + event.getPrice());
System.out.println("电影主题:" + event.getTopic());
}
}
- 定义事件发布者:
public class MyApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
public void multicastEvent(ApplicationEvent event) {
//根据不同的事件类型,选择不同监听器
if (event instanceof OrderEvent){
Collection<ApplicationListener<?>> applicationListeners = getApplicationListeners(event, ResolvableType.forInstance(event));
for (ApplicationListener listener : applicationListeners){
listener.onApplicationEvent(event);
}
}else if (event instanceof TicketEvent){
Collection<ApplicationListener<?>> applicationListeners = getApplicationListeners(event, ResolvableType.forInstance(event));
for (ApplicationListener listener : applicationListeners){
listener.onApplicationEvent(event);
}
}
}
public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
}
}
4.spring.xml 配置文件:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="orderListener" class="springBeanTest.OrderListener"/>
<bean id="ticketListener" class="springBeanTest.TicketListener"/>
<bean id="applicationEventMulticaster" class="springBeanTest.MyApplicationEventMulticaster"/>
</beans>
- 测试代码:
public class LifeCycleTest {
@Test
public void test1(){
ApplicationContext cotainer = new ClassPathXmlApplicationContext("classpath:/spring.xml");
//创建订单事件
OrderEvent orderEvent = new OrderEvent(this, "苹果", 20, 1);
//创建电影票事件
TicketEvent ticketEvent = new TicketEvent(this, 40, "爱情");
//获取事件发布者
MyApplicationEventMulticaster applicationEventMulticaster = (MyApplicationEventMulticaster) cotainer.getBean("applicationEventMulticaster");
//发布事件
System.out.println("*********************************");
applicationEventMulticaster.multicastEvent(orderEvent);
System.out.println("*********************************");
applicationEventMulticaster.multicastEvent(ticketEvent);
}
}
- 运行结果:
spring监听器原理
这一节主要讲监听器在spring容器中如何起作用的。首先分析一下AbstractApplicationContext类的refresh()方法:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
//以上代码都是作用于bean实例化之前
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// 向容器中注册配置文件中的国际化相关类实例
initMessageSource();
// 向容器注册事件发布者实例
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// 注册监听器(注意:此方法并没有实例化相关的监听器)
registerListeners();
// 初始化还没被实例化的bean(监听类在此方法中被初始化),这里的bean不单指监听实例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
- initApplicationEventMulticaster()方法讲解
此方法向容器注册事件发布者实例,如果配置了事件发布者,那么将配置对象注册到容器中,如果没有配置事件发布者,则默认将SimpleApplicationEventMulticaster对象注册到容器中。源代码如下:
protected void initApplicationEventMulticaster() {
//获取beanFactory容器
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//判断容器中是否包含ApplicationEventMulticaster实现类的beanDefinition对象
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
//如果配置了applicationEventMulticaster,则将配置的对象实例注册到容器中
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isDebugEnabled()) {
logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
//如果没有配置ApplicationEventMulticaster实现类,这将SimpleApplicationEventMulticaster对象注册到容器中
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isDebugEnabled()) {
logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
"': using default [" + this.applicationEventMulticaster + "]");
}
}
}
- registerListeners()方法讲解
此方法向容器中注册监听器,但是必须注意,此处仅仅是将容器中的监听器的名字全部存入容器中的一个set集合,并未初始化这些监听器。
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// 获取所有监听器名称
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
//获取容器中的事件发布者,然后调用事件发布者的注册监听器方法,将监听器名称存入事件发布者的监听器名称集合中。
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
}
- finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory)方法介绍
此方法的作用是实例化容器中剩余未实例化的对象,包括配置的监听器。
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
beanFactory.setConversionService(
beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
}
// Register a default embedded value resolver if no bean post-processor
// (such as a PropertyPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(new StringValueResolver() {
@Override
public String resolveStringValue(String strVal) {
return getEnvironment().resolvePlaceholders(strVal);
}
});
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// Stop using the temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
beanFactory.freezeConfiguration();
// 实例化所有非懒加载的剩余未实例化的类
beanFactory.preInstantiateSingletons();
}
到这里,事件监听的基本流程就讲解完毕
容器默认事件发布者类SimpleApplicationEventMulticaster
SimpleApplicationEventMulticaster类中有一个属性是Executor taskExecutor,作为处理事件的线程执行器,开发者可以通过setTaskExecutor(Executor taskExecutor)为其制定线程执行器。如果为设置taskExecutor的值,那么事件发布者将采用串行的方式调用所有符合条件的监听者处理监听事件。事件发布逻辑如下
public void multicastEvent(final ApplicationEvent event, ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
//筛选出所有满足条件的监听器,然后执性监听器方法
for (final ApplicationListener<?> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
//如果执行器不为空,这使用多线程处理
if (executor != null) {
executor.execute(new Runnable() {
@Override
public void run() {
invokeListener(listener, event);
}
});
}
else {
//如果执行器为空,这串行处理
invokeListener(listener, event);
}
protected void invokeListener(ApplicationListener listener, ApplicationEvent event) {
ErrorHandler errorHandler = getErrorHandler();
//如果异常处理器不为空
if (errorHandler != null) {
try {
//调用监听器方法
listener.onApplicationEvent(event);
}
catch (Throwable err) {
//发生异常时,调用异常处理器方法
errorHandler.handleError(err);
}
}
else {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
//没有异常处理器,这打印异常
String msg = ex.getMessage();
if (msg == null || msg.startsWith(event.getClass().getName())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
Log logger = LogFactory.getLog(getClass());
if (logger.isDebugEnabled()) {
logger.debug("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
}