springboot启动的时候怎么执行代码
第一种可以实现ApplicationRunner接口,代码如下
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("##################ApplicationRunner###############");
}
}

执行项目启动类main方法
控制台打印了日志信息,如下图所示,成功被执行
第二种是实现CommandLineRunner接口,代码如下图所示
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("****************************CommandLineRunner*********************");
}
}

至于为什么有这种需求,其实很多,就拿我最近的开发的功能用到了 quartz 框架来说,我们希望项目启动就去数据库当中加载定时任务的信息,然后马上在 quartz 容器当中运行,
这个时候就需要使用到了哦:


浙公网安备 33010602011771号