springboot入門、監聽、初始化、銷毀


1.新建項目

http://start.spring.io/

2.啟動

SpringApplication app = new SpringApplication(Demo1Application.class);

app.run(args);

3監聽

class ApplicationListenerEnvironmentPrepared implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
        System.out.println(getClass().getSimpleName() + "監聽...");
    }
}

class ApplicationListenerFailed implements ApplicationListener<ApplicationFailedEvent> {
    @Override
    public void onApplicationEvent(ApplicationFailedEvent event) {
        System.out.println(getClass().getSimpleName());
    }

}

class ApplicationListenerPrepared implements ApplicationListener<ApplicationPreparedEvent> {
    @Override
    public void onApplicationEvent(ApplicationPreparedEvent event) {
        System.out.println(getClass().getSimpleName());
    }

}

class ApplicationListenerStarted implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println(getClass().getSimpleName());
    }

注冊啟動類里
app.addListeners(new ApplicationListenerEnvironmentPrepared());
        app.addListeners(new ApplicationListenerFailed());
        app.addListeners(new ApplicationListenerPrepared());
        app.addListeners(new ApplicationListenerPrepared());
        app.addListeners(new ApplicationListenerStarted());
View Code

4.初始化連接等

@Component
public class TestImplApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(args);
        System.out.println("這個是測試ApplicationRunner接口");
    }

@Component
public class TestImplCommandLineRunner implements CommandLineRunner {


    @Override
    public void run(String... args) throws Exception {
    
        System.out.println("<<<<<<<<<<<<這個是測試CommandLineRunn接口>>>>>>>>>>>>>>");  
    }

}
View Code

5.銷毀

@Component
public class TestImplDisposableBean implements DisposableBean, ExitCodeGenerator {

    @Override
    public int getExitCode() {
        return 5;
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("<<<<<<<<<<<我被銷毀了......................>>>>>>>>>>>>>>>");
        System.out.println("<<<<<<<<<<<我被銷毀了......................>>>>>>>>>>>>>>>");
    }

}
View Code


免責聲明!

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



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