springboot启动后执行事件

2022-05-10  本文已影响0人  Me_tooo

一、注解@PostConstruct (最早执行)

通过一个配置类(加Component注解或者Configuration注解都可以),在里面随便写一个方法,加上PostConstruct注解即可。

@Configuration
public class MyConfig {
 @PostConstruct
 public void get(){
     System.out.println("PostConstruct");
 }
}

二、实现ApplicationListener<ApplicationStartedEvent>接口(第二执行)

@Component
public class MyApplicationListener1 implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        System.out.println("applicationStartedEvent");
    }
}

三、实现ApplicationRunner接口(第三执行)

@Component
public class MyApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner");
    }
}

四、实现CommandLineRunner接口(第四执行)

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner"+ Arrays.toString(args));
    }
}

五、实现ApplicationListener<ApplicationReadyEvent>接口(第五执行)

@Component
public class MyApplicationListener2 implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("applicationReadyEvent"+applicationReadyEvent);
    }
}

总结

以上五种方法,除了@PostConstruct注解拿不到启动时传入的参数,其他都可以。

上一篇 下一篇

猜你喜欢

热点阅读