java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot 启动时自动执行代码

SpringBoot 启动时自动执行代码的几种方式讲解

作者:字节跳跃者

本文主要介绍了SpringBoot 启动时自动执行代码的几种方式,包括static代码块、构造方法、@PostConstruct注解、ApplicationRunner和CommandLineRunner接口,感兴趣的可以了解一下

前言

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

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

Java自身的启动时加载方式

Spring启动时加载方式

代码测试

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

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.

到此这篇关于SpringBoot 启动时自动执行代码的几种方式讲解的文章就介绍到这了,更多相关SpringBoot 启动时自动执行代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文