天天看点

Spring源码系列05——Spring事件监听机制创建监听器的两个步骤

创建监听器的两个步骤

1、事件类继承ApplicationContextEvent

package com.ysy.listener;

import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.stereotype.Component;

/**
 * @author shanyangyang
 * @date 2020/9/24
 */
@Component
public class Orderevent extends ApplicationContextEvent {
	/**
	 * Create a new ContextStartedEvent.
	 *
	 * @param source the {@code ApplicationContext} that the event is raised for
	 *               (must not be {@code null})
	 */
	public Orderevent(ApplicationContext source) {
		super(source);
		System.out.println("====订单事件被初始化了====");
	}

	public void sout(){
		System.out.println("====通知别人订单被初始化了=====");
	}
}
           

2、注册监听器package com.ysy.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author shanyangyang
 * @date 2020/9/24
 * 注册lisener,也可以说是观察者
 */
@Component
public class MyListener implements ApplicationListener<Orderevent> {
	@Override public void onApplicationEvent(Orderevent event) {
		System.out.println("====监听器被触发=====");
		System.out.println("====观察者被调用====");
	}
}
           

3、测试

package com.ysy.test;

import com.ysy.aop.MathCalculator;
import com.ysy.bean.Boss;
import com.ysy.bean.Car;
import com.ysy.config.MainConfigOfAOP;
import com.ysy.config.MainConfigOfAutowired;
import com.ysy.listener.Orderevent;
import org.junit.Test;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * @author shanyangyang
 * @date 2020/6/4
 */
public class IOCTestOfAOP {
	@Test
	public void test01(){
		AnnotationConfigApplicationContext context =
				new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
		ApplicationEvent event = context.getBean(Orderevent.class);
		context.publishEvent(event);
		context.close();
	}
}
           

配置类

@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = "com.ysy.listener")
public class MainConfigOfAOP {

}
           

结果

Spring源码系列05——Spring事件监听机制创建监听器的两个步骤

发布事件,监听器方法被调用!

问题:如何在Spring创建所有的bean之后做扩展?

1、利用ContextRefreshEvent

package com.ysy.listener;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author shanyangyang
 * @date 2020/9/24
 * 监听容器已经存在的事件
 */
@Component
public class MyListener1 implements ApplicationListener<ContextRefreshedEvent> {


	@Override public void onApplicationEvent(ContextRefreshedEvent event) {
		System.out.println("====容器中的bean创建完成了=====");
	}
}
           

2、利用SmartInitializingSington

描述spring事件的原理?

使用的是观察者模式;

监听器——观察者

监听器需要注册到主题中去

事件发布器:publishevent ——主题

调用通知观察者的实现;