编程知识 cdmana.com

Spring boot starts events and listeners. It's so powerful!

Everybody knows , stay Spring Events and monitoring are everywhere in the framework , Opened the Spring The framework of the two veins of the governor , Monitoring and events are also Spring Framework must learn one of the core knowledge .

Generally speaking , We rarely use application events , But let's not forget their existence , For example, in Spring Various events are used inside the framework to handle different tasks .

without doubt , stay Spring Boot In the frame , Events and monitoring have also been promoted , Except for the common Spring Framework event ( for example :ContextRefreshedEvent) outside ,Spring Boot A series of other application events are sent during startup .

Spring Boot Start event sequence

1、ApplicationStartingEvent

This incident happened in Spring Boot When the application starts running , And send before any processing ( In addition to listener and initializer registration ).

2、ApplicationEnvironmentPreparedEvent

This event is used when known to be used in context Spring Environmental Science (Environment) when , stay Spring Context (context) Send before creating .

3、ApplicationContextInitializedEvent

This event is when  Spring Application context (ApplicationContext) Be on it , And apply the initializer (ApplicationContextInitializers) Already called , stay bean The definition of (bean definitions) Send before loading .

4、ApplicationPreparedEvent

This incident was  Spring Context (context) Before refreshing , And in bean The definition of (bean definitions) Send after loading .

5、ApplicationStartedEvent

This incident was  Spring Context (context) After refresh , And in application/ command-line runners Send before being called .

6、AvailabilityChangeEvent

This event is sent immediately after the last event , state :ReadinessState.CORRECT, Indicates that the application is already active .

7、ApplicationReadyEvent

This event is in any application/ command-line runners Send after call .

8、AvailabilityChangeEvent

This event is sent immediately after the last event , state :ReadinessState.ACCEPTING_TRAFFIC, Indicates that the application is ready to receive requests .

9、ApplicationFailedEvent

This event is sent when the application starts abnormally .


The list of events described above only includes binding to SpringApplication Of SpringApplicationEvents event , In addition to these events , The following events will also be in ApplicationPreparedEvent And after ApplicationStartedEvent Send before :

  • WebServerInitializedEvent

    This Web Server initialization events are in WebServer Send after startup , The counterpart is ServletWebServerInitializedEvent(Servlet Web Server initialization event )、ReactiveWebServerInitializedEvent( Response type Web Server initialization event ).

  • ContextRefreshedEvent

    This context refresh event is in the Spring Application context (ApplicationContext) Send after refresh .


Custom start event listener

Now that we know Spring Boot Each event in the startup process , Then we can deal with some of the things we want to do in each link , Just customize a listener to listen to an event .

For example, we want to go to the top 8 Step , That is, the application is started and can receive the request , We simply output a success flag .

Spring Boot The construction of the foundation will not be introduced here , If you are right about Spring Boot Not very familiar with , Or simply use , I suggest you study deeply , Recommend this Spring Boot Learning warehouse , welcome Star Focus on :

https://github.com/javastacks/spring-boot-best-practice

1、 New listener

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.context.ApplicationListener;

/**
 *  The official account of WeChat :Java Technology stack 
 */
@Slf4j
public class JavastackListener implements ApplicationListener<AvailabilityChangeEvent> {

    @Override
    public void onApplicationEvent(AvailabilityChangeEvent event) {
        log.info(" Listening for events :" + event);
        if (ReadinessState.ACCEPTING_TRAFFIC == event.getState()){
            log.info(" Application startup complete , Yes, please ……");
        }
    }

}

Create a new custom listener , Realized ApplicationListener Interface , Generic AvailabilityChangeEvent It means only listening AvailabilityChangeEvent event .

Indy 8 Step events and step 6 Step's event has the same name , We can distinguish which link is the event according to the state of the event .

2、 Register listener

There are two ways to register listeners :

1、 In the resource directory META-INF/spring.factories Automatically register in files :

org.springframework.context.ApplicationListener=\
cn.javastack.springboot.features.listener.JavastackListener

2、 If it's monitoring Spring Application context (ApplicationContext) Events after creation , You can use it directly on the monitor @Component Annotations can be , Otherwise you need to use the first method of automatic registration , because ApplicationContext Did not create , At this moment Bean It can't be loaded .

3、 App launch

Let's take a look at the startup log :

You can see that at the same time, the output number is 6 Step sum 8 Step monitoring log , But only output the first 8 Step start completion log , Custom monitoring implementation succeeded .

summary

I understand Spring Boot Each event and monitoring mechanism in the startup process , You can follow the example of a gourd Spring Boot Various custom actions in the startup process , For example, dynamic registration is implemented in the startup process 、 remove Bean etc. .

Generally speaking , Events and listeners are not recommended for time-consuming and onerous tasks , This will affect the normal startup of the application , Consider using Spring Boot Of application/ command-line runners To implement .

This article just introduces Spring Boot Events in the startup process and how to implement a custom listener , How to implement a business custom event and listener is beyond the scope of this article , The following stack leader opens another article , Official account Java The first time the technology stack pushes , Don't go away .

In this paper, all the source code has been uploaded :

https://github.com/javastacks/spring-boot-best-practice

Reference material :

https://docs.spring.io/spring-boot/docs/2.3.5.RELEASE/reference/htmlsingle/#boot-features-application-events-and-listeners

Last , I feel I'm getting something , Looking at 、 Forward it , Originality is not easy. , Need to be encouraged .

Copyright notice : The official account is No. "Java Technology stack " original , It's not easy to be original , Reprint 、 Please indicate the source of this article , No plagiarism 、 Manuscript preparation , Please take care of yourself , Respect other people's labor achievements and intellectual property rights .

Recommended reading
I talked about Gao recently P, I'm in a panic
Ten year old farmers , I'll teach you how to write a resume on the spot
To show you the technical article , We broke our hearts ...

 Programming · thinking · In the workplace 
 Welcome to scan 

版权声明
本文为[singwhatiwanna]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224105612934L.html

Scroll to Top