SpringBoot启动时,执行任务CommandLineRunner
在开发过程中,可能需要实现项目启动之后执行功能,Springboot提供的一种方案 就是用一个Bean或者model实现CommandLineRunner接口,将实现功能的代码放在run()方法中.
@SpringBootApplication
@ComponentScan("cn.sdut.backend")
public class ServiceApplication implements CommandLineRunner {
@Autowired
private ServiceServer server;
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
public void run(String[] args) {
server.start();
}
}
// 或者
@Component
public class MyStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
}
}
如果有多个实现类实现CommandLineRunner接口,则需要通过@Order注解来进行排序。</