Springboot中项目启动加载的几种方式

在Springboot开发的过程中,我们有时候需要在项目启动的时候提前加载或者执行一些类。

https://www.671bc1.com/Enter/home.html
一共使用过三种方法:

1、使用@PostConstruct注解;

@Component
public class MyPostConstruct {

  @PostConstruct
  public void run() {
    System.out.println("当前执行的时间:"+ LoaclDateTime.now());
  }

}

2、实现ApplicationRunner;

@Component
public class MyApplicationRunner implements ApplicationRunner {
  @Override
  public void run(ApplicationArguments args) throws Exception {
    System.out.println("当前执行的时间:"+ LoaclDateTime.now());
  }
}

3、实现CommandLineRunner。

@Component
public class MyCommandLineRunner implements CommandLineRunner {

  @Override
  public void run(String... args) throws Exception {
    System.out.println("当前执行的时间:"+ LoaclDateTime.now());
  }
}

 

 

posted @ 2025-04-04 11:50  狗狗听话  阅读(623)  评论(0)    收藏  举报