ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Spring Boot 启动时自动执行代码的几种方式

2022-07-11 09:05:28  阅读:171  来源: 互联网

标签:CommandLineRunner run Spring Boot 几种 static ApplicationRunner public 加载


来源:https://mp.weixin.qq.com/s/xHAYFaNBRys3iokdJmhzHA

  • 前言
  • java自身的启动时加载方式
  • Spring启动时加载方式
  • 代码测试
  • 总结

1.前言

目前开发的SpringBoot项目在启动的时候需要预加载一些资源。而如何实现启动过程中执行代码,或启动成功后执行,是有很多种方式可以选择,我们可以在static代码块中实现,也可以在构造方法里实现,也可以使用@PostConstruct注解实现。

当然也可以去实现Spring的ApplicationRunner与CommandLineRunner接口去实现启动后运行的功能。在这里整理一下,在这些位置执行的区别以及加载顺序。

2.java自身的启动时加载方式

2.1.static代码块

static静态代码块,在类加载的时候即自动执行。

2.2.构造方法

在对象初始化时执行。执行顺序在static静态代码块之后。

3.Spring启动时加载方式

3.1.@PostConstruct注解

PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。

3.2.ApplicationRunner和CommandLineRunner

SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner和ApplicationRunner。

这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组。

3.3.何为ApplicationArguments

官方文档解释为:Provides access to the arguments that were used to run a SpringApplication.

在Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(…)的应用参数。

3.4.Order注解

当有多个类实现了CommandLineRunner和ApplicationRunner接口时,可以通过在类上添加@Order注解来设定运行顺序。

4.代码测试

为了测试启动时运行的效果和顺序,编写几个测试代码来运行看看。

@Component
public class TestPostConstruct {

    static {
        System.out.println("static");
    }
    public TestPostConstruct() {
        System.out.println("constructer");
    }

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }
}
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("order1:TestApplicationRunner");
    }
}
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("order2:TestCommandLineRunner");
    }
}

执行结果

5.总结

Spring应用启动过程中,肯定是要自动扫描有@Component注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。

在对象注入完成后,调用带有@PostConstruct注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。

因此,加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.

标签:CommandLineRunner,run,Spring,Boot,几种,static,ApplicationRunner,public,加载
来源: https://www.cnblogs.com/no-celery/p/16465251.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有