preface

In the process of SpringBoot project started, the listener can listen in different stages corresponding event, we can through listening to the corresponding event, with some tasks, such as after start-up success to initialize the database, the operation of the table was built, and initialize the password for the administrator account, initialize the cache, a specific task registration operation, etc.

An event is a state description of the Spring Boot startup process. The events that occur during the Spring Boot startup generally refer to:

Start startup event, environment ready completion event, context ready Completion event, context load completion event, application start completion event


SpringApplicationEvents Event types

1.1 ApplicationStartingEvent

This event is sent when the Spring Boot application starts running and before any processing (except listener and initializer registrations).

1.2 ApplicationEnvironmentPreparedEvent

This event is sent when the Spring Environment is known to be used in the context before the Spring context is created.

1.3 ApplicationContextInitializedEvent

This event when the Spring application context (ApplicationContext) are ready, and application of the initializer (ApplicationContextInitializers) has been called, Send before the bean definitions are loaded.

1.4 ApplicationPreparedEvent

This event is sent before the Spring context is refreshed and after the Bean definitions have been loaded.

1.5 ApplicationStartedEvent

This event is sent after the Spring context is refreshed and before Application/Command-line Runners are called.

1.6 AvailabilityChangeEvent

This event is sent immediately after the previous event with the status: readinessState. CORRECT, indicating that the application is active.

1.7 ApplicationReadyEvent

This event is sent after any Application/Command-line Runners calls.

1.8 AvailabilityChangeEvent

This event is sent immediately after the previous event, with the status readinessstate.accepting_traffic, indicating that the application is ready to receive requests.

1.9 ApplicationFailedEvent

This event is sent when an application startup exception occurs.

How do I start listener events

2.1 Principles and Concepts

With all the Spring Boot Boot listener events mentioned above, how do you implement them? Here comes the concept of the observer model

Observer pattern: simple: what are you doing something around someone staring at you, when you do a certain thing is next to the observation of people interested in things, he will according to this to do some other things, but people staring at you must come to you to register, you won’t be able to inform him, or he has no qualification to stare at you to do things).

For some events in the Spring container, you can listen and fire the corresponding methods. There are two common methods, the ApplicationListener interface and the @EventListener annotation.

2.2 Implement the ApplicationListener interface

You need to implement the ApplicationListener interface and implement the onApplicationEvent method. The operations that need to be handled are handled in onApplicationEvent, and ApplicationListener is a generic that inherits from the parent class.

/ * * *@descriptionThe ApplicationListener interface is used to listen for message sending@author: DT
 * @date: 2021/5/10 *"@version: v1.0 * /
@Component
public class MyApplicationEventListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("ApplicationListener interface > > >"+applicationReadyEvent.toString()); }}Copy the code

2.3 Annotation via @eventListener

This approach is extremely simple, requiring only an @EventListener annotation.

@SpringBootApplication
public class JdbcApplication {

    public static void main(String[] args) {
        SpringApplication.run(JdbcApplication.class, args);
    }

    / * * *@EventListenerApplicationReadyEvent * ApplicationReadyEvent: triggered when the context is ready */
    @EventListener
    public void deploymentVer(ApplicationReadyEvent event) {
        System.out.println("Fires when context is ready >>>"+event.toString()); }}Copy the code

Iii. Case demonstration

We implemented the Spring Boot listener event in two ways above, so let’s do a simple and basic example.

3.1 Requirements: Account and password for project startup and system initialization.

3.1.1 pom. XML dependency

Here we use Jdbc to connect to the database. Here is the pom.xml core dependency code:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3. 5.RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent>Copy the code
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
Copy the code

3.1.1 Application.yml configuration file

server:
  port: 8081
spring:
  datasource:
    url: JDBC: mysql: / / 192.168.31.158:3306 / testjdbc? useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.mysql.cj.jdbc.MysqlDataSource
Copy the code

3.1.2 T_user table structure

3.1.3 listener

@EventListener
public void deploymentVer(ApplicationReadyEvent applicationReadyEvent) {
    System.out.println("System Initialization Account Password >>>"+applicationReadyEvent.toString());
    // Call the function to set the password of the system initialization account
    SystemInitUtils.initData();
}
Copy the code

3.1.4 SystemInitUtils. Java

/ * * *@description: System initialization call *@author: DT
 * @date: 2021/5/10 21:59
 * @version: v1.0 * /
public class SystemInitUtils {

    /** * System initializes the account password */
    public static void initData(a) {
        // Get the jdbcTemplate object
        JdbcTemplate jdbcTemplate = (JdbcTemplate)SpringUtils.getBean("jdbcTemplate");
        // Set the super administrator account
        long count = jdbcTemplate.queryForObject("select count(*) from t_user where username = 'admin'", Long.class);
        if(count == 0){
            Object[] args=new Object[]{"admin"."123456".new Date(),new Date()};
            jdbcTemplate.update("insert into t_user(username,password,create_time,update_time) values (? ,? ,? ,?) ",args); }}}Copy the code

3.1.5 Springutils.java common utility class

/ * * *@description: Gets the instantiated bean * from the existing Spring context@author: DT
 * @date: 2021/5/10 22:03
 * @version: v1.0 * /
@Component
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }

    public static Object getBean(String name) {
        returnapplicationContext.getBean(name); }}Copy the code

3.1.6 Starting the program

To finish, we did an example with the ApplicationReadyEvent listener event. Of course, in addition to the above two ways, we can also customize the listening event, here small editor will not explain.

conclusion

In the process of starting the SpringBoot project, the listener will listen to the corresponding events at different stages. In the following article, we will continue to do some dry things, such as initialization of the database, no longer to guide the database, no longer to create a new table field, directly through entity mapping combined with SpringBoot to start the listener event to generate table structure. This development force case is not a level, please look forward to the next chapter.