SpringApplicationRunListener 解析

SpringApplicationRunListener 作用


SpringApplicationRunListener 可以监听springboot应用启动过程中的一些生命周期事件,并做一些处理

查看SpringApplicationRunListener 定义

    /**
     * Called immediately when the run method has first started. Can be used for very
     * early initialization.
     */
    void starting();

    /**
     * Called once the environment has been prepared, but before the
     * {@link ApplicationContext} has been created.
     * @param environment the environment
     */
    void environmentPrepared(ConfigurableEnvironment environment);

    /**
     * Called once the {@link ApplicationContext} has been created and prepared, but
     * before sources have been loaded.
     * @param context the application context
     */
    void contextPrepared(ConfigurableApplicationContext context);

    /**
     * Called once the application context has been loaded but before it has been
     * refreshed.
     * @param context the application context
     */
    void contextLoaded(ConfigurableApplicationContext context);

    /**
     * Called immediately before the run method finishes.
     * @param context the application context or null if a failure occurred before the
     * context was created
     * @param exception any run exception or null if run completed successfully.
     */
    void finished(ConfigurableApplicationContext context, Throwable exception);

根据方法名可以看出对应springboot应用启动过程中的一些操作,比如

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        FailureAnalyzers analyzers = null;
        configureHeadlessProperty();
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();

这是springboot启动的时候调用的方法,对应上面的接口中的方法
如果我们自己实现这个接口,要怎么做才能让springboot启动的时候加载呢?


springboot启动的时候会在 MEAT/INF 下去找spring.factories文件
我们只需要将对应的实现类按照下面的格式配置好就行了

org.springframework.boot.SpringApplicationRunListener=com.springboot.MyApplicationRunListener

这样springboot会自动加载该实现类然后在触发事件的时候调用


版权声明:本文为u013194072原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。