CommandLineRunner的使用

版权声明:转载请取得博主同意 https://blog.csdn.net/weixin_43050247/article/details/89249394


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对象,因为它们已经初始化好了

猜你喜欢

转载自blog.csdn.net/weixin_43050247/article/details/89249394