当前位置: 代码网 > it编程>编程语言>Java > Spring事件监听器ApplicationListener的使用与原理分析

Spring事件监听器ApplicationListener的使用与原理分析

2025年11月19日 Java 我要评论
applicationevent以及listener是spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。

applicationevent以及listener是spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性。事件发布者并不需要考虑谁去监听,监听具体的实现内容是什么,发布者的工作只是为了发布事件而已。

spring提供的内置事件:

  • contextrefreshedevent:容器刷新事件
  • contextstartedevent:容器启动事件
  • contextstoppedevent:容器停止事件
  • contextclosedevent:容器关闭事件

如何使用

监听容器的刷新事件

自定义一个applicationlistener,指定监听的事件类型contextrefreshedevent:

package com.morris.spring.listener;
import org.springframework.context.applicationlistener;
import org.springframework.context.event.contextrefreshedevent;
public class contextrefreshedlistener implements applicationlistener<contextrefreshedevent> {
	@override
	public void onapplicationevent(contextrefreshedevent event) {
		system.out.println("context refresh");
	}
}

注入到容器中:

annotationconfigapplicationcontext applicationcontext = new annotationconfigapplicationcontext();
applicationcontext.register(contextrefreshedlistener.class);
applicationcontext.refresh(); 

applicationcontext.refresh()内部会发送容器刷新的事件。

自定义事件

自定义的事件需要继承applicationevent:

package com.morris.spring.event;
import org.springframework.context.applicationevent;
public class customevent extends applicationevent {
	public customevent(object source) {
		super(source);
	}
}

监听的时候使用applicationevent的子类customevent:

package com.morris.spring.listener;
import com.morris.spring.event.customevent;
import org.springframework.context.applicationlistener;
public class customeventlistener implements applicationlistener<customevent> {
	@override
	public void onapplicationevent(customevent event) {
		system.out.println("custom event: " + event.getsource());
	}
}

可以使用annotationconfigapplicationcontext发布事件:

annotationconfigapplicationcontext applicationcontext = new annotationconfigapplicationcontext();
applicationcontext.register(customeventlistener.class);
applicationcontext.refresh();
applicationcontext.publishevent(new customevent("custom event"));

可以向bean中注入一个applicationeventpublisher来发布事件:

package com.morris.spring.service;
import com.morris.spring.event.customevent;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.applicationeventpublisher;
public class customeventservice {
	@autowired
	private applicationeventpublisher applicationeventpublisher;
	public void publishevent() {
		applicationeventpublisher.publishevent(new customevent("自定义事件"));
	}
}

可以通过实现applicationeventpublisheraware接口注入applicationeventpublisher来发布事件:

package com.morris.spring.service;
import com.morris.spring.event.customevent;
import org.springframework.context.applicationeventpublisher;
import org.springframework.context.applicationeventpublisheraware;
public class customeventservice2 implements applicationeventpublisheraware {
	private applicationeventpublisher applicationeventpublisher;
	public void publishevent() {
		applicationeventpublisher.publishevent(new customevent("自定义事件"));
	}
	@override
	public void setapplicationeventpublisher(applicationeventpublisher applicationeventpublisher) {
		this.applicationeventpublisher = applicationeventpublisher;
	}
}

由于applicationcontext实现了applicationeventpublisher接口,也可以直接注入applicationcontext来发布事件。

使用@eventlistener监听事件

在监听事件时,由于类需要实现applicationlistener接口,对代码有很大的侵入性,可以使用@eventlistener注解随时随地监听事件,这样一个service中可以监听多个事件:

package com.morris.spring.listener;
import com.morris.spring.event.customevent;
import org.springframework.context.applicationlistener;
import org.springframework.context.event.contextrefreshedevent;
import org.springframework.context.event.eventlistener;
public class customeventlistener2 {
	@eventlistener
	public void listencontextrefreshedevent(contextrefreshedevent event) {
		system.out.println("context refresh");
	}
	@eventlistener
	public void listencustomevent(customevent event) {
		system.out.println("custom event: " + event.getsource());
	}
}

还可以在@eventlistener注解上指定监听的事件类型:

package com.morris.spring.listener;
import com.morris.spring.event.customevent;
import org.springframework.context.applicationevent;
import org.springframework.context.event.contextrefreshedevent;
import org.springframework.context.event.eventlistener;
public class customeventlistener3 {
	@eventlistener({contextrefreshedevent.class, customevent.class})
	public void listenevent(applicationevent event) {
		system.out.println(event);
	}
}

异步发送消息

spring消息的发送默认都是同步的,如果要异步发送消息,首先要在配置类上开启异步功能@enableasync:

package com.morris.spring.config;
import org.springframework.context.annotation.configuration;
import org.springframework.scheduling.annotation.enableasync;
@configuration
@enableasync // 开启异步
public class eventlistenerconfig {
}

在监听的方法上加上@async:

package com.morris.spring.listener;
import com.morris.spring.event.customevent;
import lombok.extern.slf4j.slf4j;
import org.springframework.context.applicationevent;
import org.springframework.context.event.contextrefreshedevent;
import org.springframework.context.event.eventlistener;
import org.springframework.scheduling.annotation.async;
@slf4j
public class asynccustomeventlistener {
	@eventlistener({contextrefreshedevent.class, customevent.class})
	@async // 异步
	public void listenevent(applicationevent event) {
		log.info("receive event: {}", event);
	}
}

也可以自定义执行异步消息的线程池(默认就是simpleasynctaskexecutor):

@bean
public taskexecutor executor() {
	return new simpleasynctaskexecutor("eventlisten-");
}

异步消息只是借用spring的异步执行机制,在方法上加上@async注解,方法都会异步执行。

applicationlistener原理分析

发布消息的入口

发布消息入口:
org.springframework.context.support.abstractapplicationcontext#publishevent(org.springframework.context.applicationevent)

public void publishevent(applicationevent event) {
    publishevent(event, null);
}
protected void publishevent(object event, @nullable resolvabletype eventtype) {
...
        /**
         * @see simpleapplicationeventmulticaster#multicastevent(org.springframework.context.applicationevent, org.springframework.core.resolvabletype)
         */
        // 发布消息
        getapplicationeventmulticaster().multicastevent(applicationevent, eventtype);
    }
... ...
}

然后调用simpleapplicationeventmulticaster来进行广播消息:

// org.springframework.context.event.simpleapplicationeventmulticaster#multicastevent(org.springframework.context.applicationevent, org.springframework.core.resolvabletype)
public void multicastevent(final applicationevent event, @nullable resolvabletype eventtype) {
    resolvabletype type = (eventtype != null ? eventtype : resolvedefaulteventtype(event));
    // 如果有线程池,将会异步执行
    executor executor = gettaskexecutor();
    for (applicationlistener<?> listener : getapplicationlisteners(event, type)) {
        if (executor != null) {
            executor.execute(() -> invokelistener(listener, event));
        }
        else {
            invokelistener(listener, event);
        }
    }
}
protected void invokelistener(applicationlistener<?> listener, applicationevent event) {
    errorhandler errorhandler = geterrorhandler();
    if (errorhandler != null) {
        try {
            doinvokelistener(listener, event);
        }
        catch (throwable err) {
            errorhandler.handleerror(err);
        }
    }
    else {
        // applicationlistener.调用onapplicationevent
        doinvokelistener(listener, event);
    }
}
private void doinvokelistener(applicationlistener listener, applicationevent event) {
    try {
        listener.onapplicationevent(event);
    }
    catch (classcastexception ex) {
        string msg = ex.getmessage();
        if (msg == null || matchesclasscastmessage(msg, event.getclass())) {
            // possibly a lambda-defined listener which we could not resolve the generic event type for
            // -> let's suppress the exception and just log a debug message.
            log logger = logfactory.getlog(getclass());
            if (logger.istraceenabled()) {
                logger.trace("non-matching event type for listener: " + listener, ex);
            }
        }
        else {
            throw ex;
        }
    }
}

何时注入simpleapplicationeventmulticaster

从上面的源码可以发现spring是通过simpleapplicationeventmulticaster事件多播器来发布消息的,那么这个类是何时注入的呢?容器refresh()时。

org.springframework.context.support.abstractapplicationcontext#initapplicationeventmulticaster

protected void initapplicationeventmulticaster() {
	configurablelistablebeanfactory beanfactory = getbeanfactory();
	if (beanfactory.containslocalbean(application_event_multicaster_bean_name)) {
		this.applicationeventmulticaster =
				beanfactory.getbean(application_event_multicaster_bean_name, applicationeventmulticaster.class);
		if (logger.istraceenabled()) {
			logger.trace("using applicationeventmulticaster [" + this.applicationeventmulticaster + "]");
		}
	}
	else {
		// 直接new,然后放入到spring一级缓存中
		this.applicationeventmulticaster = new simpleapplicationeventmulticaster(beanfactory);
		beanfactory.registersingleton(application_event_multicaster_bean_name, this.applicationeventmulticaster);
		if (logger.istraceenabled()) {
			logger.trace("no '" + application_event_multicaster_bean_name + "' bean, using " +
					"[" + this.applicationeventmulticaster.getclass().getsimplename() + "]");
		}
	}
}

何时注入applicationlistener

spring在发布消息时,会从simpleapplicationeventmulticaster中拿出所有的applicationlistener,那么这些applicationlistener何时被注入的呢?容器refresh()时。

org.springframework.context.support.abstractapplicationcontext#registerlisteners

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
	// uninitialized to let post-processors apply to them!
	string[] listenerbeannames = getbeannamesfortype(applicationlistener.class, true, false);
	for (string listenerbeanname : listenerbeannames) {
		// 添加到simpleapplicationeventmulticaster中
		getapplicationeventmulticaster().addapplicationlistenerbean(listenerbeanname);
	}
	// publish early application events now that we finally have a multicaster...
	set<applicationevent> earlyeventstoprocess = this.earlyapplicationevents;
	this.earlyapplicationevents = null;
	if (!collectionutils.isempty(earlyeventstoprocess)) {
		for (applicationevent earlyevent : earlyeventstoprocess) {
			getapplicationeventmulticaster().multicastevent(earlyevent);
		}
	}
}

@eventlistener的原理

@eventlistener注解的功能是通过eventlistenermethodprocessor来实现的,eventlistenermethodprocessor这个类在annotationconfigapplicationcontext的构造方法中被注入。

eventlistenermethodprocessor主要实现了两个接口:smartinitializingsingleton和beanfactorypostprocessor。

先来看看beanfactorypostprocessor的postprocessbeanfactory(),这个方法主要是保存beanfactory和eventlistenerfactories,后面的方法将会使用到:

public void postprocessbeanfactory(configurablelistablebeanfactory beanfactory) {
    // 保存beanfactory
    this.beanfactory = beanfactory;
    /**
     * eventlistenerfactory[defaulteventlistenerfactory]在何处被注入?
     * @see annotationconfigutils#registerannotationconfigprocessors(org.springframework.beans.factory.support.beandefinitionregistry, java.lang.object)
     */
    map<string, eventlistenerfactory> beans = beanfactory.getbeansoftype(eventlistenerfactory.class, false, false);
    list<eventlistenerfactory> factories = new arraylist<>(beans.values());
    annotationawareordercomparator.sort(factories);
    // 保存eventlistenerfactories
    this.eventlistenerfactories = factories;
}

再来看看smartinitializingsingleton的aftersingletonsinstantiated()方法,这个方法会在所有的bean初始化完后执行。

public void aftersingletonsinstantiated() {
	configurablelistablebeanfactory beanfactory = this.beanfactory;
	assert.state(this.beanfactory != null, "no configurablelistablebeanfactory set");
	string[] beannames = beanfactory.getbeannamesfortype(object.class);
	for (string beanname : beannames) {
		if (!scopedproxyutils.isscopedtarget(beanname)) {
			// 目标类的类型
			class<?> type = null;
			try {
				type = autoproxyutils.determinetargetclass(beanfactory, beanname);
			}
			catch (throwable ex) {
				// an unresolvable bean type, probably from a lazy bean - let's ignore it.
				if (logger.isdebugenabled()) {
					logger.debug("could not resolve target class for bean with name '" + beanname + "'", ex);
				}
			}
			if (type != null) {
				if (scopedobject.class.isassignablefrom(type)) {
					try {
						class<?> targetclass = autoproxyutils.determinetargetclass(
								beanfactory, scopedproxyutils.gettargetbeanname(beanname));
						if (targetclass != null) {
							type = targetclass;
						}
					}
					catch (throwable ex) {
						// an invalid scoped proxy arrangement - let's ignore it.
						if (logger.isdebugenabled()) {
							logger.debug("could not resolve target bean for scoped proxy '" + beanname + "'", ex);
						}
					}
				}
				try {
					// 处理目标对象
					processbean(beanname, type);
				}
				catch (throwable ex) {
					throw new beaninitializationexception("failed to process @eventlistener " +
							"annotation on bean with name '" + beanname + "'", ex);
				}
			}
		}
	}
}
private void processbean(final string beanname, final class<?> targettype) {
	if (!this.nonannotatedclasses.contains(targettype) &&
			annotationutils.iscandidateclass(targettype, eventlistener.class) &&
			!isspringcontainerclass(targettype)) {
		map<method, eventlistener> annotatedmethods = null;
		try {
			// 获得类中所有的带有@eventlistener注解的方法
			annotatedmethods = methodintrospector.selectmethods(targettype,
					(methodintrospector.metadatalookup<eventlistener>) method ->
							annotatedelementutils.findmergedannotation(method, eventlistener.class));
		}
		catch (throwable ex) {
			// an unresolvable type in a method signature, probably from a lazy bean - let's ignore it.
			if (logger.isdebugenabled()) {
				logger.debug("could not resolve methods for bean with name '" + beanname + "'", ex);
			}
		}
		if (collectionutils.isempty(annotatedmethods)) {
			this.nonannotatedclasses.add(targettype);
			if (logger.istraceenabled()) {
				logger.trace("no @eventlistener annotations found on bean class: " + targettype.getname());
			}
		}
		else {
			// non-empty set of methods
			configurableapplicationcontext context = this.applicationcontext;
			assert.state(context != null, "no applicationcontext set");
			list<eventlistenerfactory> factories = this.eventlistenerfactories;
			assert.state(factories != null, "eventlistenerfactory list not initialized");
			for (method method : annotatedmethods.keyset()) {
				for (eventlistenerfactory factory : factories) {
					if (factory.supportsmethod(method)) {
						method methodtouse = aoputils.selectinvocablemethod(method, context.gettype(beanname));
						// 使用factory创建一个applicationlistener
						applicationlistener<?> applicationlistener =
								factory.createapplicationlistener(beanname, targettype, methodtouse);
						if (applicationlistener instanceof applicationlistenermethodadapter) {
							((applicationlistenermethodadapter) applicationlistener).init(context, this.evaluator);
						}
						// 将applicationlistener添加到spring容器中
						context.addapplicationlistener(applicationlistener);
						break;
					}
				}
			}
			if (logger.isdebugenabled()) {
				logger.debug(annotatedmethods.size() + " @eventlistener methods processed on bean '" +
						beanname + "': " + annotatedmethods);
			}
		}
	}
}

springboot中的事件

springboot在启动时会按以下顺序发送消息:

  1. applicationstartingevent:在运行开始时发送 ,但在进行任何处理之前(侦听器和初始化程序的注册除外)发送
  2. applicationenvironmentpreparedevent:当被发送environment到中已知的上下文中使用,但是在创建上下文之前
  3. applicationcontextinitializedevent:在applicationcontext准备好且已调用applicationcontextinitializers之后但任何bean定义未加载之前发送
  4. applicationpreparedevent:在刷新开始之前但在加载bean定义之后发送
  5. applicationstartedevent:上下文已被刷新后发送,但是任何应用程序和命令行都被调用前
  6. applicationreadyevent:在所有的命令行应用启动后发送此事件,可以处理请求
  7. applicationfailedevent:在启动时异常发送

到此这篇关于spring事件监听器applicationlistener的使用与源码分析的文章就介绍到这了,更多相关spring applicationlistener使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com