问题描述:项目中配置事件监听,监听当容器加载完成以后,作一些初始化工做。项目运行以后,发现初始化工做被重复作了两次。为了便于分析,去掉代码中的业务逻辑,只留下场景。java
@Component
public class FreshListener implements ApplicationListener<ContextRefreshedEvent>{
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//业务代码
logger.error("将有权限人员放入缓存。。。。");
}
}
复制代码
配置FreshListener监听器,监听当容器加载完成以后,将管理员名单加入缓存。却发现,名单被加载了两次。WHY???spring
因为源码中的个方法较长,因此只贴出重点且与主题相关的代码。建议结合本地源码一块儿看。缓存
public class User {
private String username;
private String password;
private String sms;
public User(String username, String password, String sms) {
this.username = username;
this.password = password;
this.sms = sms;
}
}
复制代码
public interface UserListener extends EventListener {
void onRegister(UserEvent event);
}
复制代码
public class SendSmsListener implements UserListener {
@Override
public void onRegister(UserEvent event) {
if (event instanceof SendSmsEvent) {
Object source = event.getSource();
User user = (User) source;
System.out.println("send sms to " + user.getUsername());
}
}
}
复制代码
public class UserEvent extends EventObject {
public UserEvent(Object source){
super(source);
}
}
复制代码
public class SendSmsEvent extends UserEvent {
public SendSmsEvent(Object source) {
super(source);
}
}
复制代码
public class UserService {
private List<UserListener> listenerList = new ArrayList<>();
//当用户注册的时候,触发发送短信事件
public void register(User user){
System.out.println("name= " + user.getUsername() + " ,password= " +
user.getPassword() + " ,注册成功");
publishEvent(new SendSmsEvent(user));
}
public void publishEvent(UserEvent event){
for(UserListener listener : listenerList){
listener.onRegister(event);
}
}
public void addListeners(UserListener listener){
this.listenerList.add(listener);
}
}
复制代码
public class EventApp {
public static void main(String[] args) {
UserService service = new UserService();
service.addListeners(new SendSmsListener());
//添加其余监听器 ...
User user = new User("foo", "123456", "注册成功啦!!");
service.register(user);
}
}
复制代码
/**
* A tagging interface that all event listener interfaces must extend.
* @since JDK1.1
*/
public interface EventListener {
}
复制代码
该接口为标识接口bash
/**
* <p>
* The root class from which all event state objects shall be derived.
* <p>
* All Events are constructed with a reference to the object, the "source",
* that is logically deemed to be the object upon which the Event in question
* initially occurred upon.
* @since JDK1.1
*/
public class EventObject implements java.io.Serializable {
private static final long serialVersionUID = 5516075349620653480L;
/**
* The object on which the Event initially occurred.
*/
protected transient Object source;
/**
* Constructs a prototypical Event.
* @param source The object on which the Event initially occurred.
* @exception IllegalArgumentException if source is null.
*/
public EventObject(Object source) {
if (source == null)
throw new IllegalArgumentException("null source");
this.source = source;
}
/**
* The object on which the Event initially occurred.
* @return The object on which the Event initially occurred.
*/
public Object getSource() {
return source;
}
/**
* Returns a String representation of this EventObject.
* @return A a String representation of this EventObject.
*/
public String toString() {
return getClass().getName() + "[source=" + source + "]";
}
}
复制代码
该接口中仅有source参数,无特殊含义,相似于存放数据源微信
对比上面jdk事件的Demo,我们分析spring源码app
咱们以前分析了Spring中bean是如何加载的,而且分析了项目启动的入口,不作赘叙,将其做为已知条件。ide
@Override
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);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
}
}
复制代码
这个方法中有三句话与Spring事件相关,把这三句话分析明白了,Spring事件机制也就了然了。挨个分析:源码分析
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
复制代码
从容器中的全部bean中获取实现ApplicationListener接口的类。换言之,若是咱们想使用Spring 事件机制来为咱们项目服务,那咱们所写的监听器必须实现ApplicationListener接口。post
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
/**
* Handle an application event.
* @param event the event to respond to
*/
void onApplicationEvent(E event);
}
复制代码
ApplicationListener接口继承自jdk事件机制中的EventListener,能够看出Spring事件机制改编自jdk事件机制。Spring在监听器接口中添加了onApplicationEvent()方法,便于事件被触发时执行任务,相似于上午UserListener中的onRegister()方法。
回到registerListeners()方法,获取到监听器类以后,存放在了事件广播器(applicationEventMulticaster)中,便于后面使用。测试
publishEvent(new ContextRefreshedEvent(this));
复制代码
这句话相似于UserService中的publishEvent(new SendSmsEvent(user)),而ContextRefreshedEvent相似于上文中的发送短信事件。ContextRefreshedEvent表明的事件是容器初始化完成。若是容器初始化完成了,那么所对应的事件监听器将会被触发。继续层层跟进,来到:
publishEvent(Object event, ResolvableType eventType)
复制代码
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
复制代码
getApplicationListeners(event, type)
复制代码
这句话的意思是根据事件类型获取监听器。由于我们在项目里面可能会配置不少监听器,每个监听器都会有本身所对应的事件类型,只有本身所对应的事件发生了,监听器才会被触发。
invokeListener(listener, event);
复制代码
doInvokeListener(listener, event);
复制代码
listener.onApplicationEvent(event);
复制代码
看到了onApplicationEvent在此执行了,相似于UserService中listener.onRegister(event)。
至此,事件机制分析完毕。
// Publish event via parent context as well...
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
复制代码
判断该容器是否有父容器,若存在入容器,再一次触发父容器中的事件监听器。
从上文的源码分析中,我们知道了ContextRefreshedEvent事件监听器是在refresh()方法内被触发的,更准确地讲,是refresh()方法中的finishRefresh()触发了ContextRefreshedEvent事件监听器。而咱们在以前的文章中,得出一个结论:子容器能够获取父容器bean,反之不行。这里是由于Spring容器初始化执行refresh()方法时,触发了ContextRefreshedEvent事件监听器,而SpringMvc容器初始化时也执行了refresh()方法,当代码执行到
publishEvent(Object event, ResolvableType eventType);
复制代码
其中有一段代码判断了是否存在父容器。若存在,会将父容器中的监听器执行一遍。因此再一次触发了ContextRefreshedEvent事件监听器。因此从直观上看,初始化了两次。
@Component
public class EvolvedFreshListener implements ApplicationListener<ContextRefreshedEvent>{
private final Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null){
logger.error("进化版====将有权限人员放入缓存。。。。");
}
}
}
复制代码
/**
* 实现此类, 能够在Spring容器彻底初始化完毕时获取到Spring容器
*/
public abstract class ContextRefreshListener implements
ApplicationListener<ContextRefreshedEvent> {
private volatile boolean initialized = false;
@Override
public synchronized void onApplicationEvent(ContextRefreshedEvent event) {
if (!initialized) {
System.out.println("加锁====将有权限人员放入缓存。。。。");
initialized = true
}
}
}复制代码
BLOG地址:www.liangsonghua.me
关注微信公众号:松花皮蛋的黑板报,获取更多精彩!
公众号介绍:分享在京东工做的技术感悟,还有JAVA技术和业内最佳实践,大部分都是务实的、能看懂的、可复现的