springboot应用中使用CommandLineRunner

在springboot应用中,存在这样的使用场景,在springboot ioc容器创建好之后根据业务需求先执行一些操作,springboot提供了两个接口可以实现该功能:

  1. CommandLineRunner
  2. ApplicatioinRunner

使用思路:

  1. 实现改接口,重写run方法,run方法中完成要完成的操作
  2. 实例化接口,并注入到spring ioc容器
/**
 * Application类
 */
@SpringBootApplication
public class Application implements CommandLineRunner {
    @Resource
    private HelloService helloService;

    public static void main(String[] args) {
        System.out.println(" 容器创建之前");
        SpringApplication.run(Application.class, args);
        System.out.println("容器创建之后");
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("前面过程在创建容器,现在创建好了,先执行下列操作:");
        //调用run方法时,spring ioc容器中helloService已经创建并装配好
        helloService.sayHello("操作:arminker");
    }
}

总结

  1. @SpringBootApplication标注的类是一个配置类
  2. 在springboot应用中,配置类对象会自动被spring ioc容器所管理
  3. 在测试类中,使用AnnotationConfigApplicationContext获取容器对象,发现无法获取,说明在非springboot项目中,被@Configuration标注的类不会对项目进行自动配置,必须要添加配置参数。

Original: https://www.cnblogs.com/arminker/p/15781545.html
Author: 流云的博客
Title: springboot应用中使用CommandLineRunner

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/684921/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球