CommandLineRunner的使用

本文深入解析SpringBoot中CommandLineRunner接口的两种实现方式:继承接口与@Bean结合使用,阐述其在应用启动后执行一次性逻辑的重要性和应用场景,如依赖bean对象进行springbatch任务触发。


springboot的 CommandLineRunner 接口主要用于实现应用初始化之后,去执行一段逻辑代码,并且在整个项目的声明周期中,执行一次,源码如下:

package org.springframework.boot;

public interface CommandLineRunner {
    void run(String... var1) throws Exception;
}

1.两种实现方式

1.1继承CommandLineRunner接口

和注解 @Componerent一起使用,如果涉及到多个,用@Order()注解去设置执行顺序

@Component
@Order(value = 1)
public class CLR1 implements CommandLineRunner{
public void run(String... strings) throws Exception {
     //do something
   }
}

@Component
@Order(value = 2)
public class CLR2 implements CommandLineRunner{
public void run(String... strings) throws Exception {
     //do something
   }
}

1.2 和@Bean连用,返回CommandLineRunner实例

@Bean
public CommandLineRunner initialize(SomeModel ModelInstance) {
    return (abc) -> {
        ModelInstance.dosomething(...)
    };
}

该方法需要放在有@Component/@SpringBootApplication注解的类上
abc为任意字符,SomeModel ModelInstance 为用Spring bean对象,controller中可用@Resource@Autowired接收

2.为什么要使用CommandLineRunner

  • 实现在应用启动后,去执行相关代码逻辑,且只会执行一次
  • spring batch批量处理框架依赖这些执行器去触发执行任务
  • 可以使用依赖,bean对象,因为它们已经初始化好了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值