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

公众号程序猿DD

共 2693字,需浏览 6分钟

 · 2022-05-31

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

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

java自身的启动时加载方式

static代码块

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

构造方法

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

Spring启动时加载方式

@PostConstruct注解

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

ApplicationRunner和CommandLineRunner

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

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

何为ApplicationArguments

官方文档解释为:

Provides access to the arguments that were used to run a SpringApplication.

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

Order注解

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

如果你正在学习Spring Boot,推荐一个免费教程:http://blog.didispace.com/spring-boot-learning-2x/,教程还有配套仓库,每个知识点都有案例可以直接运行和参考,赶紧Star收藏起来吧~

  • Github:https://github.com/dyc87112/SpringBoot-Learning/
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning/

代码测试

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

TestPostConstruct

@Component
public class TestPostConstruct {

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

    @PostConstruct
    public void init() {
        System.out.println("PostConstruct");
    }
}

TestApplicationRunner

@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("order1:TestApplicationRunner");
    }
}

TestCommandLineRunner

@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.out.println("order2:TestCommandLineRunner");
    }
}

执行结果

总结

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

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

因此,加载顺序为static>constructer>@PostConstruct>CommandLineRunnerApplicationRunner.

我们创建了一个高质量的技术交流群,与优秀的人在一起,自己也会优秀起来,赶紧点击加群,享受一起成长的快乐。另外,如果你最近想跳槽的话,年前我花了2周时间收集了一波大厂面经,节后准备跳槽的可以点击这里领取

推荐阅读

··································

你好,我是程序猿DD,10年开发老司机、阿里云MVP、腾讯云TVP、出过书创过业、国企4年互联网6年从普通开发到架构师、再到合伙人。一路过来,给我最深的感受就是一定要不断学习并关注前沿。只要你能坚持下来,多思考、少抱怨、勤动手,就很容易实现弯道超车!所以,不要问我现在干什么是否来得及。如果你看好一个事情,一定是坚持了才能看到希望,而不是看到希望才去坚持。相信我,只要坚持下来,你一定比现在更好!如果你还没什么方向,可以先关注我,这里会经常分享一些前沿资讯,帮你积累弯道超车的资本。

点击领取2022最新10000T学习资料
浏览 20
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报