SpringBoot启动时执行特定的任务

本文介绍了在SpringBoot项目启动时如何利用CommandLineRunner接口执行特定任务。通过实现该接口的run方法,可以在项目初始化阶段运行自定义代码。如果存在多个实现类,可以使用@Order注解来设定执行顺序。
摘要由CSDN通过智能技术生成

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注解来进行排序。</

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值