Springboot初始化资源的几种方式
在Spring Boot中,可以使用多种方式来跟随项目启动,以下是其中的几种方式:
- 使用CommandLineRunner接口
实现CommandLineRunner接口,并重写run方法,该方法会在Spring Boot应用启动时执行。例如:
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 在应用启动时执行的代码
}
}
- 使用ApplicationRunner接口
实现ApplicationRunner接口,并重写run方法,该方法会在Spring Boot应用启动时执行。与CommandLineRunner不同的是,ApplicationRunner的run方法接收一个ApplicationArguments对象作为参数,该对象可以获取应用启动时传递的参数。例如: