实现SpringBoot应用启动时运行特定代码
前言
在SpringBoot应用启动的时候一般都会初始化一些数据到应用中,这时就要运行一些特定的代码,可以通过实现ApplicationRunner或CommandLineRunner接口,重写接口的run方法,来达到这样的效果
一、实现ApplicationRunner接口
实现代码为:
@Component
public class InitInfo implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("This is an init information");
}
}
注意:这里要把实现类加入到IOC容器中,不然SpringBoot没法识别,也不会执行run方法里面打的代码
二、实现CommandLineRunner接口
实现代码为:
@Component
public class InitData implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Initializing");
}
}
总结
在SpringBoot应用启动的时候,想要执行我们指定的代码片段,可以通过实现ApplicationRunner或CommandLineRunner接口,重写唯一的run方法,以达到目的。需要特别注意的是:需要把实现类加入到IOC容器中,交给SpringBoot管理,这样SpringBoot才能够帮我们自动执行。