Spring Boot Application 事件和監聽器


一:Application 事件

(1)ApplicationStartingEvent

  An ApplicationStartingEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.

 (2)ApplicationEnvironmentPreparedEvent

An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.

示例:

public class MyListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {

    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent  event) {
        SpringApplication app = event.getSpringApplication();
//        app.setBannerMode(Banner.Mode.OFF);
        System.out.println("#####MyListener found!#####");
    }
}

Application類中添加

@SpringBootApplication
public class Application {
    public static void main(String[] args){
        SpringApplication app = new SpringApplication(Application.class);
        app.addListeners(new MyListener());
        app.run(args);
    }
}

運行結果:

 

 (3)ApplicationPreparedEvent

    An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.

(4)ApplicationReadyEvent 

    An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.

當Application啟動好后調用

示例:

public class MyListener implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(ApplicationReadyEvent  event) {
        System.out.println("#####MyListener found!#####");
    }
}

 

運行結果位置:

 

(5)ApplicationFailedEvent 

    An ApplicationFailedEvent is sent if there is an exception on startup.

這里舉了兩種事件的例子,其他3種事件可以通過改寫MyListener中參數調試。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM