关于java:Spring-Boot-启动时自动执行代码的几种方式还有谁不会

9次阅读

共计 2104 个字符,预计需要花费 6 分钟才能阅读完成。

起源:blog.csdn.net/u011291072/article/details/81813662

前言

目前开发的 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 根底就不介绍了,举荐下这个实战教程:https://github.com/javastacks…

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.

近期热文举荐:

1.1,000+ 道 Java 面试题及答案整顿(2022 最新版)

2. 劲爆!Java 协程要来了。。。

3.Spring Boot 2.x 教程,太全了!

4. 别再写满屏的爆爆爆炸类了,试试装璜器模式,这才是优雅的形式!!

5.《Java 开发手册(嵩山版)》最新公布,速速下载!

感觉不错,别忘了顺手点赞 + 转发哦!

正文完
 0