• 项目初始化时ApplicationRunner和CommandLineRunner的应用


    1.Application运行之前需要执行一些代码,可以通过实现ApplicationRunner或者CommandLineRunner接口。接口只有一个run方法,会在SpringApplication.run(...)方法执行之前运行。其中ApplicationRunner可以访问ApplicationArguments参数信息;而CommandLineRunner可以访问原始的String[]参数,当程序启动时,我们传给main()方法的参数可以被实现CommandLineRunner和ApplicationRunner接口的类的run()方法访问,即可接收启动服务时传过来的参数。我们可以创建多个实现CommandLineRunner和ApplicationRunner接口的类。为了使他们按一定顺序执行,可以使用@Order注解或实现Ordered接口  主要应用于执行某些逻辑。可用于项目的准备工作,比如加载配置文件,加载执行流,定时任务等

    ApplicationRunner接口实现:

    CommandLineRunner接口示例

    在spring boot程序中,我们可以使用不止一个实现CommandLineRunner和ApplicationRunner的bean。为了有序执行这些bean的run()方法,可以使用@Order注解或Ordered接口  如以上写的

    @Order(value = 1)   
    @Order(value = 2)

    执行顺序如下:

     另外,通过分析springboot启动的源码可以发现,在applicationContext容器加载完成之后,会调用SpringApplication类的callRunners方法:该方法中会获取所有实现了ApplicationRunner和CommandLineRunner的接口bean,然后依次执行对应的run方法,并且是在同一个线程中执行。因此如果有某个实现了ApplicationRunner接口的bean的run方法一直循环不返回的话,后续的代码将不会被执行

    2.ApplicationRunner、InitializingBean、@PostConstruct执行顺序问题

    InitializingBean接口的用法

    InitializingBean接口为bean提供了初始化方法的方式,它只包括afterPropertiesSet方法,凡是继承该接口的类,在初始化bean的时候都会执行该方法。注意,实现该接口的最好加上Spring的注解注入,比如@Component

    @PostConstruct注解的用法

    如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。 优先级: Constructor >> @Autowired >> @PostConstruct

     

    @PostConstruct>InitializingBean>ApplicationRunner>CommandLineRunner,当然如果涉及到类中的static代码块,则是:
    static>@PostConstruct>InitializingBean>ApplicationRunner>CommandLineRunner

    最后看下实际项目中的应用 如连接netty服务器:

     

     

     

  • 相关阅读:
    leetcode6132. 使数组中所有元素都等于零(简单,周赛)
    【11】c++11新特性 —>move移动语义(2)
    VoLTE题库(含解析)-中高级必看
    iPad 使用技巧:虚拟键盘与实体键盘
    elementui实现input输入框和textarea文本框回车换行
    【k8s】浅谈对kubernetes基本概念
    客户画像分析无头绪?来试下风险评分与特征的方案与实现
    FastAdmin框架实现数据表的增删改查
    Split to Be Slim: 论文复现
    人工智能未来可期:超越人类能力的新科技
  • 原文地址:https://blog.csdn.net/weixin_39643007/article/details/126525293