ApplicationListener 就是spring的监听器,能够用来监听事件,典型的观察者模式。
使用方法:
public class MyListern implements ApplicationListener {
@Override
public void onApplicationEvent(MyEvent2 event) {
System.out.println("哈哈");
}
}
public static void main(String[] args) {
ConfigurableApplicationContext configurableApplicationContext = SpringApplication.run(DemoApplication.class, args);
configurableApplicationContext.addApplicationListener(new MyListern());
configurableApplicationContext.publishEvent(new MyEvent2("a"));
}
通过山下文的addApplicationListener来进行注册监听器
@Override
public void addApplicationListener(ApplicationListener> listener) {
Assert.notNull(listener, "ApplicationListener must not be null");
if (this.applicationEventMulticaster != null) {
this.applicationEventMulticaster.addApplicationListener(listener);
}
else {
this.applicationListeners.add(listener);
}
}
从这个可以看出本质上其实是把监听器加入了上下文内部的SimpleApplicationEventMulticaster对象中
通过configurableApplicationContext. publishEvent来进行事件的发布。
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Publishing event in " + getDisplayName() + ": " + event);
}
// Decorate event as an ApplicationEvent if necessary
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// 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);
}
}
}
这边还是使用了SimpleApplicationEventMulticaster来进行通知
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
for (final ApplicationListener> listener : getApplicationListeners(event, type)) {
Executor executor = getTaskExecutor();
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
获得对应事件的所有实现类进行回调通知
注册监听的几种方式:
- 1: @component
@Component
public class MyListern implements ApplicationListener {
@Override
public void onApplicationEvent(MyEvent2 event) {
System.out.println("哈哈");
}
}
- 2: 通过应用上下文的addApplicationListener的加入
- 3: 通过 @EventListener注解加入
@EventListener
public String handleDemoEvent(MyEvent2 myEvent) {
System.out.println("我监听到了pulisher发布的message为:");
return "a";
}
第一种方式 原理还没有看后续补上
第二种方式上面已经讲过
第三种方式原理:
第三种方式的实现主要是靠EventListenerMethodProcessor 这个类来完成的
@Override
public void afterSingletonsInstantiated() {
List factories = getEventListenerFactories();
ConfigurableApplicationContext context = getApplicationContext();
String[] beanNames = context.getBeanNamesForType(Object.class);
for (String beanName : beanNames) {
if (!ScopedProxyUtils.isScopedTarget(beanName)) {
Class> type = null;
try {
type = AutoProxyUtils.determineTargetClass(context.getBeanFactory(), 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(
context.getBeanFactory(), 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(factories, beanName, type);
}
catch (Throwable ex) {
throw new BeanInitializationException("Failed to process @EventListener " +
"annotation on bean with name '" + beanName + "'", ex);
}
}
}
}
}
这边方法的主要作用就是在所有的单列都初始化完成后 解析bean结构看里面是否有 @EventListener注解
protected void processBean(
final List factories, final String beanName, final Class> targetType) {
if (!this.nonAnnotatedClasses.contains(targetType)) {
Map annotatedMethods = null;
try {
annotatedMethods = MethodIntrospector.selectMethods(targetType,
(MethodIntrospector.MetadataLookup) 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 = getApplicationContext();
for (Method method : annotatedMethods.keySet()) {
for (EventListenerFactory factory : factories) {
if (factory.supportsMethod(method)) {
Method methodToUse = AopUtils.selectInvocableMethod(method, context.getType(beanName));
ApplicationListener> applicationListener =
factory.createApplicationListener(beanName, targetType, methodToUse);
if (applicationListener instanceof ApplicationListenerMethodAdapter) {
((ApplicationListenerMethodAdapter) applicationListener).init(context, this.evaluator);
}
context.addApplicationListener(applicationListener);
break;
}
}
}
if (logger.isDebugEnabled()) {
logger.debug(annotatedMethods.size() + " @EventListener methods processed on bean '" +
beanName + "': " + annotatedMethods);
}
}
}
}
有的话就会通过DefaultEventListenerFactory生成一个ApplicationListenerMethodAdapter类来作为监听加入contentx中
看下ApplicationListenerMethodAdapter监听类内部的回调方法:
@Override
public void onApplicationEvent(ApplicationEvent event) {
processEvent(event);
}
/**
* Process the specified {@link ApplicationEvent}, checking if the condition
* match and handling non-null result, if any.
*/
public void processEvent(ApplicationEvent event) {
Object[] args = resolveArguments(event);
if (shouldHandle(event, args)) {
Object result = doInvoke(args);
if (result != null) {
handleResult(result);
}
else {
logger.trace("No result object given - no result to handle");
}
}
}
可以看出内部是通过反射的机制进行了通知
}
protected void handleResult(Object result) {
if (result.getClass().isArray()) {
Object[] events = ObjectUtils.toObjectArray(result);
for (Object event : events) {
publishEvent(event);
}
}
else if (result instanceof Collection>) {
Collection> events = (Collection>) result;
for (Object event : events) {
publishEvent(event);
}
}
else {
publishEvent(result);
}
}
这边可以看出使用@EventListener注解的监听可以根据返回值继续调用监听