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

简介: SpringBoot 启动时自动执行代码的几种方式

前言


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


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


java自身的启动时加载方式


static代码块


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


构造方法


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


Spring启动时加载方式


@PostConstruct注解


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


ApplicationRunner和CommandLineRunner


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


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


什么是ApplicationArguments


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


Order注解


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


代码测试


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


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");
    }
}


执行结果

1673365823425.jpg


总结


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


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


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

相关文章
|
6月前
|
Java
springboot启动时执行
springboot启动时执行
36 0
|
5天前
|
数据库
Springboot+mybatis-plus逆向工程生成代码器
Springboot+mybatis-plus逆向工程生成代码器
|
5天前
|
Java 测试技术 数据库
SpringBoot启动时设置不加载数据库
SpringBoot启动时设置不加载数据库
16 0
|
5天前
|
存储 前端开发 Java
基于SpringBoot实现文件上传和下载(详细讲解And附完整代码)
基于SpringBoot实现文件上传和下载(详细讲解And附完整代码)
|
5天前
|
存储 JavaScript 前端开发
基于SpringBoot的医护人员排班系统(代码+数据库+文档)
基于SpringBoot的医护人员排班系统(代码+数据库+文档)
|
5天前
|
前端开发 Java 数据库连接
基于SpringBoot宠物领养系统的设计与实现(代码+数据库+文档)
基于SpringBoot宠物领养系统的设计与实现(代码+数据库+文档)
|
5天前
|
存储 Java 数据库
基于springboot的医院信息管理系统(程序+代码+文档)
基于springboot的医院信息管理系统(程序+代码+文档)
|
5天前
|
存储 前端开发 Java
基于springboot的图书管理系统(代码+数据库+文档)
基于springboot的图书管理系统(代码+数据库+文档)
|
5天前
|
存储 Java API
你了解SpringBoot启动时API相关信息是用什么数据结构存储的吗?(上篇)
你了解SpringBoot启动时API相关信息是用什么数据结构存储的吗?(上篇)
36 0
|
5天前
|
Java
SpringBoot - 使用Assert校验让业务代码更简洁
SpringBoot - 使用Assert校验让业务代码更简洁
49 0

相关实验场景

更多