In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces "what are the core classes and interfaces mainly involved in the Spring event monitoring mechanism". In the daily operation, I believe that many people have doubts about the core classes and interfaces mainly involved in the Spring event monitoring mechanism. The editor consulted all kinds of materials and sorted out simple and useful operation methods. I hope it will be helpful for you to answer the question of "what are the core classes and interfaces involved in the Spring event monitoring mechanism?" Next, please follow the editor to study!
Spring event listening mechanism
In fact, there is a set of event listening mechanism in the Spring/ Spring Boot framework, which can implement the observer pattern.
There are also many events built into the Spring/ Spring Boot framework, and we can also customize publish application events, which we will describe below.
The core classes and interfaces involved are as follows:
ApplicationEvent
ApplicationEvent (application event) is an abstract class that corresponds to an observation target in the observer pattern.
The ApplicationEvent source code is as follows:
Public abstract class ApplicationEvent extends EventObject {/ * * use serialVersionUID from Spring 1.2 for interoperability. * / private static final long serialVersionUID = 7099057708183571937L; / * System time when the event happened. * / private final long timest / * * Create a new {@ code ApplicationEvent}. * @ param source the object on which the event initially occurred or with * which the event is associated (never {@ code null}) * / public ApplicationEvent (Object source) {super (source); this.timestamp = System.currentTimeMillis ();} / * * Return the system time in milliseconds when the event occurred. * / public final long getTimestamp () {return this.timest}}
ApplicationEvent inherits from the EventObject event object class in Java, and all events in the Spring framework inherit from the ApplicationEvent class, which is the parent class of all events.
The main core of ApplicationEvent is the class constructor, which initializes an source event association object to get and notify updates in the event listener.
ApplicationListener
ApplicationListener (application event listener) is an interface that is equivalent to an observer in observer mode.
The ApplicationListener source code is as follows:
Public interface ApplicationListener extends EventListener {/ * * Handle an application event. * @ param event the event to respond to * / void onApplicationEvent (E event);}
ApplicationListener inherits from the EventListener event listener interface in Java. There is only one onApplicationEvent method in the ApplicationListener class. When the specified listening event is published, it will be triggered and executed. You can obtain the associated object in the event through event.
ApplicationEventPublisher
The application event publishing interface encapsulates the basic interface of the event publishing function.
Public interface ApplicationEventPublisher {/ * * Notify all matching listeners registered with this * application of an application event. Events may be framework events * (such as ContextRefreshedEvent) or application-specific events. *
Such an event publication step is effectively a hand-off to the * multicaster and does not imply synchronous/asynchronous execution * or even immediate execution at all. Event listeners are encouraged * to be as efficient as possible, individually using asynchronous * execution for longer-running and potentially blocking operations. * @ param event the event to publish * @ see # publishEvent (Object) * @ see org.springframework.context.event.ContextRefreshedEvent * @ see org.springframework.context.event.ContextClosedEvent * / default void publishEvent (ApplicationEvent event) {publishEvent ((Object) event);} / * Notify all matching listeners registered with this * application of an event. *
If the specified {@ code event} is not an {@ link ApplicationEvent}, * it is wrapped in a {@ link PayloadApplicationEvent}. *
Such an event publication step is effectively a hand-off to the * multicaster and does not imply synchronous/asynchronous execution * or even immediate execution at all. Event listeners are encouraged * to be as efficient as possible, individually using asynchronous * execution for longer-running and potentially blocking operations. * @ param event the event to publish * @ since 4.2 * @ see # publishEvent (ApplicationEvent) * @ see PayloadApplicationEvent * / void publishEvent (Object event);}
ApplicationEventPublisher has a default interface method and interface method, which needs to be implemented by a specific subclass container.
ApplicationContext
The class ApplicationContext, which is the core container in the Spring framework, is all too familiar.
As shown in the following figure, the ApplicationContext interface inherits the ApplicationEventPublisher interface, so the commonly used ApplicationContext can be used to publish events.
The Spring event monitoring and publishing roles described above are strung together to publish an ApplicationEvent event and associate an event object through an ApplicationEventPublisher or ApplicationContext container, and then ApplicationListener listens to the event. When the event is published, the listener will receive execution and obtain the event and associated object.
Spring Boot observer mode actual combat
Having understood the event and listening mechanism in the Spring framework, let's modify it with the example of the observer pattern in the above article.
The basic knowledge and building process of Spring Boot will not be introduced. If you are not familiar with it, you can follow the official account Java technology stack and reply the keyword "boot" in the background to read the series of tutorials I wrote before.
The source code of all Spring Boot tutorials is located in the following warehouse:
Https://github.com/javastacks/spring-boot-best-practice
Added observer target class import lombok.Getter; import org.springframework.context.ApplicationEvent; / * * observation target: stack length * Source Wechat official account: Java technology stack * / @ Getter public class JavaStackEvent extends ApplicationEvent {/ * * Create a new {@ code ApplicationEvent}. * * @ param source the object on which the event initially occurred or with * which the event is associated (never {@ code null}) * / public JavaStackEvent (Object source) {super (source);}
Implementing the ApplicationEvent application event interface in the Spring framework is equivalent to an observer goal.
New Observer import lombok.NonNull; import lombok.RequiredArgsConstructor; import org.springframework.context.ApplicationListener; import org.springframework.scheduling.annotation.Async; / * Observer: reader fans * Source Wechat official account: Java Technology Stack * / @ RequiredArgsConstructor public class ReaderListener implements ApplicationListener {@ NonNull private String name; private String article @ Async @ Override public void onApplicationEvent (JavaStackEvent event) {/ / Update the article updateArticle (event);} private void updateArticle (JavaStackEvent event) {this.article = (String) event.getSource (); System.out.printf ("I am the reader:% s, the article has been updated to:% s\ n", this.name, this.article);}}
Implement the ApplicationListener application listening interface in the Spring framework, which is equivalent to an observer.
The structure of the observation target and observer class is as follows:
New test configuration class import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @ Slf4j @ Configuration public class ObserverConfiguration {@ Bean public CommandLineRunner commandLineRunner (ApplicationContext context) {return (args)-> {log.info ("release event: what is Observer Mode?") ; context.publishEvent (new JavaStackEvent ("what is observer mode?") ;}; @ Bean public ReaderListener readerListener1 () {return new ReaderListener ("Xiao Ming");} @ Bean public ReaderListener readerListener2 () {return new ReaderListener ("Xiao Zhang");} @ Bean public ReaderListener readerListener3 () {return new ReaderListener ("Xiao Love");}}
Three reader Bean are created in the Spring configuration, one observer mode event is published after the Spring Boot starts, and then the three Bean are notified.
Output result:
It may not be appropriate to create a Bean for each reader here, because you want to mimic the application of the previous observer pattern.
In practice, the application of observer mode should refer to specific business. For example, in an e-commerce payment scenario, a payment event can be published after the user has paid, and then there will be deductions. A series of follow-up event listeners such as SMS notification and coupons can be used to decouple the business. This is a typical application scenario.
At this point, the study of "what are the core classes and interfaces mainly involved in the Spring event monitoring mechanism" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
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: 282
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.