Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the Spring/SpringBoot event listening mechanism?

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)05/31 Report--

What this article shares with you is about what the Spring/SpringBoot event monitoring mechanism is. The editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

Event monitoring mechanism can be understood as an observer mode, with data publishers (event sources) and data receivers (listeners).

In Java, event objects are inherited java.util.EventObject objects, and event listeners are java.util.EventListener instances

The EventObject object does not provide a default constructor, so you need to pass the source parameter externally, that is, to record and track the source of the event

Spring event

The Spring event object is ApplicationEvent and inherits EventObject. The source code is as follows:

Public abstract class ApplicationEvent extends EventObject {/ * * Create a new ApplicationEvent. * @ param source the object on which the event initially occurred (never {@ code null}) * / public ApplicationEvent (Object source) {super (source); this.timestamp = System.currentTimeMillis ();}}

The Spring event listener is ApplicationListener and inherits EventListener. The source code is as follows:

Public interface ApplicationListener extends EventListener {void onApplicationEvent (E var1);}

There are two ways to implement Spring event listening:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Interface-oriented programming to realize ApplicationListener interface

Based on annotation-driven, @ EventListener (Spring custom annotations)

Example:

Interface-oriented programming to implement ApplicationListener interface:

Custom event object:

Public class MyApplicationEvent extends ApplicationEvent {public MyApplicationEvent (Object source) {super (source);}}

Custom event listeners:

Public class MyApplicationListener implements ApplicationListener {@ Override public void onApplicationEvent (MyApplicationEvent event) {System.out.println ("received event:" + event);}}

Start the service and publish the event:

Public class ApplicationEventBootstrap {public static void main (String [] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (); / register custom event listener context.addApplicationListener (new MyApplicationListener ()); / / launch context context.refresh (); / / publish event, event source is Context context.publishEvent (new MyApplicationEvent (context)) / / end context.close ();}}

Running result:

Received event: com.xx.MyApplicationEvent [source=org.springframework.context.annotation.AnnotationConfigApplicationContext@cb0ed20, started on Sat May 16 16:32:04 CST 2020]

Use the annotation @ EventListener to implement Spring event listening:

@ Component public class MyApplicationListener2 {@ EventListener (MyApplicationEvent.class) public void onEvent (MyApplicationEvent event) {System.out.println ("received event:" + event);}}

Start and publish the event:

Public class ApplicationEventBootstrap {public static void main (String [] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext (); / register custom event listener context.register (MyApplicationListener2.class); / / launch context context.refresh (); / / publish event, event source is Context context.publishEvent (new MyApplicationEvent (context)) / / end context.close ();}}

Running result:

Received event: com.xx.MyApplicationEvent [source=org.springframework.context.annotation.AnnotationConfigApplicationContext@cb0ed20, started on Sat May 16 16:32:04 CST 2020]

As can be seen from the examples, the above two ways can publish and receive events normally.

Realization principle

As you can see from the above example, context can publish events. How is it released at the bottom? let's continue to look at the source code:

Public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {protected void publishEvent (Object event, @ Nullable ResolvableType eventType) {... GetApplicationEventMulticaster (). MulticastEvent (applicationEvent, eventType);

From the source code, we can see that the event should be through the

Released by ApplicationEventMulticaster, let's move on to:

Public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster

Events in Spring are published through the

SimpleApplicationEventMulticaster to realize it.

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) {/ / Asynchronous executor.execute (()-> invokeListener (listener, event));} else {invokeListener (listener, event) }

You can see that if Executor is set, it is sent asynchronously, otherwise synchronously; and you can see that the published event type is checked through resolveDefaultEventType (event), which is why we can directly use generics to specify the event objects we want to receive, such as ApplicationListener above.

Private void doInvokeListener (ApplicationListener listener, ApplicationEvent event) {try {listener.onApplicationEvent (event)

Finally, just use the corresponding ApplicationListener for receiving and processing, so when did the ApplicationListener register?

How do I add ApplicationListener?

Add directly, using content.addApplicationListener (used in the above example)

After registering the custom ApplicationListener as a Bean,Spring and then initializing the Bean, it will be added. The specific code is in ApplicationListenerDetector#postProcessAfterInitialization. If a Bean is ApplicationListener, it is also added using context.addApplicationListener.

Using the annotation @ EventListener, after initializing the Bean, it is processed and added in the EventListenerMethodProcessor

The source code for the third implementation is as follows

In EventListenerMethodProcessor):

Private void processBean (final String beanName, final Class targetType) {.... / / get public and have @ EventListener method AnnotatedElementUtils.findMergedAnnotation (method, EventListener.class); ApplicationListener applicationListener = factory.createApplicationListener (beanName, targetType, methodToUse); / / add listener context.addApplicationListener (applicationListener);}

Spring built-in event

ContextRefreshedEvent: Spring application context ready event

ContextStartedEvent: Spring application context launch event

ContextStopedEvent: Spring application context stop event

ContextClosedEvent: Spring application context shutdown event

Spring Boot event

Spring Boot events are encapsulated on the basis of Spring events

Public abstract class SpringApplicationEvent extends ApplicationEvent

The event object is changed to SpringApplicationEvent, and the event source is SpringApplication (Spring event source is Context)

The underlying release event still uses the

SimpleApplicationEventMulticaster object, but it is important to note that since Spring Boot 1.4, both SpringApplication and ApplicationContext have used

SimpleApplicationEventMulticaster instance, but they belong to different objects (version 1.0-1.3 is the same object)

Event Review:

Public class EventBootstrap {public static void main (String [] args) {new SpringApplicationBuilder (Object.class) .listeners (event-> {System.out.println ("event object:" + event.getClass () .getSimpleName () + ", event source:" + event.getSource () .getClass () .listeners () ) .web (WebApplicationType.NONE) .run (args) .close ();}}

Running result:

Event object: ApplicationContextInitializedEvent, event source: SpringApplication event object: ApplicationPreparedEvent, event source: SpringApplication event object: ContextRefreshedEvent, event source: AnnotationConfigApplicationContext event object: ApplicationStartedEvent, event source: SpringApplication event object: ApplicationReadyEvent, event source: SpringApplication event object: ContextClosedEvent, event source: AnnotationConfigApplicationContext

As can be seen from the results, the event object type and event source, as well as the event release order.

This is what the Spring/SpringBoot event monitoring mechanism is, and the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report