0
点赞
收藏
分享

微信扫一扫

SpringBoot CommandLineRunner接口的使用

老牛走世界 2022-03-12 阅读 51

1. 使用场景

在项目服务启动的时候就去加载一些数据或者做一些批处理
如果是批处理的话,可以将项目打成jar包,供其他程序调用


2. 原理

Spring Boot应用程序在启动后,会从容器中遍历实现了CommandLineRunner接口的实例并运行它们的run方法,所以实现CommandLineRunner的类需要添加@Component等注解。如果有多个类实现了CommandLineRunner接口的话,也可以利用@Order注解来规定所有CommandLineRunner实例的运行顺序。


3.实现

⏹定义接口

public interface IMethod {
    void run();
}

⏹接口实现类

// 给bean取别名
@Component("batchA")
public class Batch1 implements IMethod {

    public void run() {
        System.out.println("Batch1执行了");
    }
}

// 给bean取别名
@Component("batchB")
public class Batch2 implements IMethod {

    public void run() {
        System.out.println("Batch2执行了");
    }
}

⏹CommandLineRunner 接口的实现类

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

// 实现CommandLineRunner接口的类需要添加@Component等注解,把实现类放到Spring容器中
@Component
public class ParamExecute1 implements CommandLineRunner {
	
	// 注入ApplicationContext对象,获取容器中的Bean
    @Autowired
    private ApplicationContext applicationContext;
	
	// args为从控制台传入的参数
    public void run(String... args) throws Exception {

        if (ObjectUtils.isEmpty(args)) {
            System.out.println("_/_/_/_/_/_/_/_/_/_/_/_/_/");
            System.out.println("请传入参数");
            return;
        }
		
		// 获取传入的第一个参数(参数值和IMethod接口实现类的别名要相同)
        String arg = args[0];
        try {
        	
        	// 根据Bean名称和IMethod接口获取到实现了IMethod接口的实现类对象
            IMethod bean = applicationContext.getBean(arg, IMethod.class);
            bean.run();
        } catch (Exception e) {
            System.out.println("_/_/_/_/_/_/_/_/_/_/_/_/_/");
            System.out.println("请传入正确的参数");
        }
    }
}

⏹打包为jar包之后,控制台调用
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考资料
1.https://blog.csdn.net/cx1110162/article/details/87866633
2.https://www.cnblogs.com/lucky9322/p/13289751.html

举报

相关推荐

0 条评论