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