美文网首页
springboot启动后执行事件

springboot启动后执行事件

作者: Me_tooo | 来源:发表于2022-05-10 09:51 被阅读0次

一、注解@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注解拿不到启动时传入的参数,其他都可以。

相关文章

网友评论

      本文标题:springboot启动后执行事件

      本文链接:https://www.haomeiwen.com/subject/ymlhurtx.html