SpringBoot啓動的事件監聽機制原理解析

一,前言
前面說了SpringBoot的啓動原理(如果對SpringBoot啓動原理不熟悉的朋友可以先看這篇SpringBoot的啓動原理),本篇就繼續趁熱打鐵說說整個啓動過程中的事件監聽機制原理:
主要有以下幾個事件和監聽機制
1ApplicationContextInitializer
2SpringApplicationRunListener
3ApplicationRunner
4CommandLineRunner

  1. ApplicationContextInitializer
    實現ApplicationContextInitializer泛型接口:
    首先進入ApplicationContextInitializer接口查看其實現類,我們接下來可以借鑑
    在這裏插入圖片描述
    可以看到只有一個初始化方法需要實現:
public class BTApplicationContextIinitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>{
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer.......此時該容器開始初始化了"+applicationContext);
    }

}
  1. SpringApplicationRunListener
    Spring應用監聽器主要是用來監聽Spring應用的整個啓動過程,所以會有多個方法
    需要注意的地方,必須要寫上一個有參構造方法來接收SpringApplication對象,否則會報錯:
    Caused by: java.lang.NoSuchMethodException: com.springxxxt.demo.listener.BTSpringApplicationRunListener.(org.springframework.boot.SpringApplication, [Ljava.lang.String;)
public class BTSpringApplicationRunListener implements SpringApplicationRunListener, Ordered {


    public BTSpringApplicationRunListener(SpringApplication application, String[] args){

    }

    @Override
    public int getOrder() {
        return 0;
    }
    //初始化啓動
    @Override
   public  void starting() {
       System.out.println("SpringApplicationRunListener.....開始運行");
    }
    //環境準備
    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
       Object o=environment.getSystemProperties().get("os.name");
       System.out.println("ConfigurableEnvironment......Prepared"+o);
    }
    //容器準備
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
       System.out.println("ConfigurableApplicationContext.....contextPrepared"+context.getClass());
    }
    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("ConfigurableApplicationContext.....contextLoaded"+context.getClass());
    }
    //容器開始
    @Override
    public  void started(ConfigurableApplicationContext context) {
        System.out.println("ConfigurableApplicationContext.....started"+context.getClass());
    }

    //運行
    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("ConfigurableApplicationContext.....running"+context.getClass());
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }
    private static class LoggingErrorHandler implements ErrorHandler {
        private static final Log logger = LogFactory.getLog(EventPublishingRunListener.class);

        private LoggingErrorHandler() {
        }

        public void handleError(Throwable throwable) {
            logger.warn("Error calling ApplicationEventListener", throwable);
        }
    }
}
  1. ApplicationRunner
    需要注意使用Component註解將該類加入到容器中去,否則無效
@Component //將該類加入到容器中去
public class BTApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationArguments......run");
    }
}
  1. CommandLineRunner
    此類和Application一樣都是從IOC容器中獲取的,同樣需要使用Component註解
@Component   //將該類加入到容器中去
public class BTCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner......run"+ Arrays.asList(args));
    }
}

最後,也是最重要的一步, ApplicationContextInitializer和SpringApplicationRunListener都是SpringApplication對象創建時,從類路徑META-INF/spring.factories下獲取的,所以我們需要建立META-INF/spring.factories目錄結構,並參照springBoot 的格式將我們自定義的類路徑寫到配置文件中

# Initializers
org.springframework.context.ApplicationContextInitializer=\
com.springxxxt.demo.listener.BTApplicationContextIinitializer

# Run Listeners
org.springframework.boot.SpringApplicationRunListener=\
com.springxxxt.demo.listener.BTSpringApplicationRunListener

這樣我們就可以啓動SpringBoot應用了,在控制檯可以看到我們自定義的信息:

"G:\IDEA\IntelliJ IDEA 2019.2.4\jbr\bin\java.exe" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dspring.jmx.enabled=true -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true "-javaagent:G:\IDEA\IntelliJ IDEA 2019.2.4\lib\idea_rt.jar=64822:G:\IDEA\IntelliJ IDEA 2019.2.4\bin" -Dfile.encoding=UTF-8 -classpath D:\XXXTX\target\classes;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-data-jdbc\2.2.4.RELEASE\spring-boot-starter-data-jdbc-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\data\spring-data-jdbc\1.1.4.RELEASE\spring-data-jdbc-1.1.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\data\spring-data-relational\1.1.4.RELEASE\spring-data-relational-1.1.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\data\spring-data-commons\2.2.4.RELEASE\spring-data-commons-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-tx\5.2.3.RELEASE\spring-tx-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-context\5.2.3.RELEASE\spring-context-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-beans\5.2.3.RELEASE\spring-beans-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\slf4j\slf4j-api\1.7.30\slf4j-api-1.7.30.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-data-jpa\2.2.4.RELEASE\spring-boot-starter-data-jpa-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-aop\2.2.4.RELEASE\spring-boot-starter-aop-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-aop\5.2.3.RELEASE\spring-aop-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\aspectj\aspectjweaver\1.9.5\aspectjweaver-1.9.5.jar;C:\Users\PC\.m2\repository\jakarta\activation\jakarta.activation-api\1.2.1\jakarta.activation-api-1.2.1.jar;C:\Users\PC\.m2\repository\jakarta\persistence\jakarta.persistence-api\2.2.3\jakarta.persistence-api-2.2.3.jar;C:\Users\PC\.m2\repository\jakarta\transaction\jakarta.transaction-api\1.3.3\jakarta.transaction-api-1.3.3.jar;C:\Users\PC\.m2\repository\org\hibernate\hibernate-core\5.4.10.Final\hibernate-core-5.4.10.Final.jar;C:\Users\PC\.m2\repository\org\jboss\logging\jboss-logging\3.4.1.Final\jboss-logging-3.4.1.Final.jar;C:\Users\PC\.m2\repository\org\javassist\javassist\3.24.0-GA\javassist-3.24.0-GA.jar;C:\Users\PC\.m2\repository\net\bytebuddy\byte-buddy\1.10.6\byte-buddy-1.10.6.jar;C:\Users\PC\.m2\repository\antlr\antlr\2.7.7\antlr-2.7.7.jar;C:\Users\PC\.m2\repository\org\jboss\jandex\2.1.1.Final\jandex-2.1.1.Final.jar;C:\Users\PC\.m2\repository\com\fasterxml\classmate\1.5.1\classmate-1.5.1.jar;C:\Users\PC\.m2\repository\org\dom4j\dom4j\2.1.1\dom4j-2.1.1.jar;C:\Users\PC\.m2\repository\org\hibernate\common\hibernate-commons-annotations\5.1.0.Final\hibernate-commons-annotations-5.1.0.Final.jar;C:\Users\PC\.m2\repository\org\glassfish\jaxb\jaxb-runtime\2.3.2\jaxb-runtime-2.3.2.jar;C:\Users\PC\.m2\repository\org\glassfish\jaxb\txw2\2.3.2\txw2-2.3.2.jar;C:\Users\PC\.m2\repository\com\sun\istack\istack-commons-runtime\3.0.8\istack-commons-runtime-3.0.8.jar;C:\Users\PC\.m2\repository\org\jvnet\staxex\stax-ex\1.8.1\stax-ex-1.8.1.jar;C:\Users\PC\.m2\repository\com\sun\xml\fastinfoset\FastInfoset\1.2.16\FastInfoset-1.2.16.jar;C:\Users\PC\.m2\repository\org\springframework\data\spring-data-jpa\2.2.4.RELEASE\spring-data-jpa-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-orm\5.2.3.RELEASE\spring-orm-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-aspects\5.2.3.RELEASE\spring-aspects-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-jdbc\2.2.4.RELEASE\spring-boot-starter-jdbc-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter\2.2.4.RELEASE\spring-boot-starter-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot\2.2.4.RELEASE\spring-boot-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.2.4.RELEASE\spring-boot-autoconfigure-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-logging\2.2.4.RELEASE\spring-boot-starter-logging-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;C:\Users\PC\.m2\repository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;C:\Users\PC\.m2\repository\org\apache\logging\log4j\log4j-to-slf4j\2.12.1\log4j-to-slf4j-2.12.1.jar;C:\Users\PC\.m2\repository\org\apache\logging\log4j\log4j-api\2.12.1\log4j-api-2.12.1.jar;C:\Users\PC\.m2\repository\org\slf4j\jul-to-slf4j\1.7.30\jul-to-slf4j-1.7.30.jar;C:\Users\PC\.m2\repository\jakarta\annotation\jakarta.annotation-api\1.3.5\jakarta.annotation-api-1.3.5.jar;C:\Users\PC\.m2\repository\org\yaml\snakeyaml\1.25\snakeyaml-1.25.jar;C:\Users\PC\.m2\repository\com\zaxxer\HikariCP\3.4.2\HikariCP-3.4.2.jar;C:\Users\PC\.m2\repository\org\springframework\spring-jdbc\5.2.3.RELEASE\spring-jdbc-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-web\2.2.4.RELEASE\spring-boot-starter-web-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-json\2.2.4.RELEASE\spring-boot-starter-json-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.10.2\jackson-databind-2.10.2.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\core\jackson-annotations\2.10.2\jackson-annotations-2.10.2.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\core\jackson-core\2.10.2\jackson-core-2.10.2.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.10.2\jackson-datatype-jdk8-2.10.2.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.10.2\jackson-datatype-jsr310-2.10.2.jar;C:\Users\PC\.m2\repository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.10.2\jackson-module-parameter-names-2.10.2.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-tomcat\2.2.4.RELEASE\spring-boot-starter-tomcat-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\org\apache\tomcat\embed\tomcat-embed-core\9.0.30\tomcat-embed-core-9.0.30.jar;C:\Users\PC\.m2\repository\org\apache\tomcat\embed\tomcat-embed-el\9.0.30\tomcat-embed-el-9.0.30.jar;C:\Users\PC\.m2\repository\org\apache\tomcat\embed\tomcat-embed-websocket\9.0.30\tomcat-embed-websocket-9.0.30.jar;C:\Users\PC\.m2\repository\org\springframework\boot\spring-boot-starter-validation\2.2.4.RELEASE\spring-boot-starter-validation-2.2.4.RELEASE.jar;C:\Users\PC\.m2\repository\jakarta\validation\jakarta.validation-api\2.0.2\jakarta.validation-api-2.0.2.jar;C:\Users\PC\.m2\repository\org\hibernate\validator\hibernate-validator\6.0.18.Final\hibernate-validator-6.0.18.Final.jar;C:\Users\PC\.m2\repository\org\springframework\spring-web\5.2.3.RELEASE\spring-web-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-webmvc\5.2.3.RELEASE\spring-webmvc-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-expression\5.2.3.RELEASE\spring-expression-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\mybatis\spring\boot\mybatis-spring-boot-starter\1.3.2\mybatis-spring-boot-starter-1.3.2.jar;C:\Users\PC\.m2\repository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\1.3.2\mybatis-spring-boot-autoconfigure-1.3.2.jar;C:\Users\PC\.m2\repository\org\mybatis\mybatis-spring\1.3.2\mybatis-spring-1.3.2.jar;C:\Users\PC\.m2\repository\com\alibaba\druid\1.1.16\druid-1.1.16.jar;C:\Users\PC\.m2\repository\mysql\mysql-connector-java\8.0.19\mysql-connector-java-8.0.19.jar;C:\Users\PC\.m2\repository\jakarta\xml\bind\jakarta.xml.bind-api\2.3.2\jakarta.xml.bind-api-2.3.2.jar;C:\Users\PC\.m2\repository\org\springframework\spring-core\5.2.3.RELEASE\spring-core-5.2.3.RELEASE.jar;C:\Users\PC\.m2\repository\org\springframework\spring-jcl\5.2.3.RELEASE\spring-jcl-5.2.3.RELEASE.jar com.springxxxt.demo.DemoApplication
SpringApplicationRunListener.....開始運行
ConfigurableEnvironment......PreparedWindows 8.1

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

ApplicationContextInitializer.......此時該容器開始運行了org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@797b0699, started on Thu Jan 01 08:00:00 CST 1970
ConfigurableApplicationContext.....contextPreparedclass org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
2020-02-01 11:55:06.940  INFO 2148 --- [           main] com.springxxxt.demo.DemoApplication      : Starting DemoApplication on Lenovo-PC with PID 2148 (D:\XXXTX\target\classes started by PC in D:\XXXTX)
2020-02-01 11:55:06.946  INFO 2148 --- [           main] com.springxxxt.demo.DemoApplication      : No active profile set, falling back to default profiles: default
ConfigurableApplicationContext.....contextLoadedclass org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
2020-02-01 11:55:13.145  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-02-01 11:55:13.167  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JDBC repositories in DEFAULT mode.
2020-02-01 11:55:13.455  INFO 2148 --- [           main] .RepositoryConfigurationExtensionSupport : Spring Data JDBC - Could not safely identify store assignment for repository candidate interface com.springxxxt.demo.Dao.JPARepository. If you want this repository to be a JDBC repository, consider annotating your entities with one of these annotations: org.springframework.data.relational.core.mapping.Table.
2020-02-01 11:55:13.457  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 252ms. Found 0 JDBC repository interfaces.
2020-02-01 11:55:13.510  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2020-02-01 11:55:13.510  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2020-02-01 11:55:13.594  INFO 2148 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 52ms. Found 1 JPA repository interfaces.
2020-02-01 11:55:14.956  INFO 2148 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-02-01 11:55:18.775  INFO 2148 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-02-01 11:55:18.831  INFO 2148 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-02-01 11:55:18.831  INFO 2148 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-02-01 11:55:18.833  INFO 2148 --- [           main] o.a.catalina.core.AprLifecycleListener   : An older version [1.2.18] of the APR based Apache Tomcat Native library is installed, while Tomcat recommends a minimum version of [1.2.23]
2020-02-01 11:55:18.833  INFO 2148 --- [           main] o.a.catalina.core.AprLifecycleListener   : Loaded APR based Apache Tomcat Native library [1.2.18] using APR version [1.6.5].
2020-02-01 11:55:18.833  INFO 2148 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR capabilities: IPv6 [true], sendfile [true], accept filters [false], random [true].
2020-02-01 11:55:18.833  INFO 2148 --- [           main] o.a.catalina.core.AprLifecycleListener   : APR/OpenSSL configuration: useAprConnector [false], useOpenSSL [true]
2020-02-01 11:55:18.951  INFO 2148 --- [           main] o.a.catalina.core.AprLifecycleListener   : OpenSSL successfully initialized [OpenSSL 1.1.1  11 Sep 2018]
2020-02-01 11:55:19.492  INFO 2148 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-02-01 11:55:19.492  INFO 2148 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 12233 ms
2020-02-01 11:55:20.769  INFO 2148 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-02-01 11:55:21.079  INFO 2148 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.4.10.Final}
2020-02-01 11:55:23.254  INFO 2148 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
2020-02-01 11:55:27.934  INFO 2148 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2020-02-01 11:55:28.186  INFO 2148 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL57Dialect
2020-02-01 11:55:32.539  INFO 2148 --- [           main] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-02-01 11:55:32.704  INFO 2148 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-02-01 11:55:34.524  WARN 2148 --- [           main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-02-01 11:55:35.004  INFO 2148 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-02-01 11:55:36.020  INFO 2148 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-02-01 11:55:36.023  INFO 2148 --- [           main] com.springxxxt.demo.DemoApplication      : Started DemoApplication in 37.145 seconds (JVM running for 83.554)
ConfigurableApplicationContext.....startedclass org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
ApplicationArguments......run
CommandLineRunner......run[]
ConfigurableApplicationContext.....runningclass org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章