当前位置: 首页 > news >正文

springboot实现项目启动前的一些操作

在服务启动时,做一些操作,比如加载配置,初始化数据,请求其他服务的接口等。
有三种方法:

第一种是实现CommandLineRunner接口
第二种是实现ApplicationRunner接口
第三种是使用注解:@PostConstruct
三者使用方法
先看下三种方法分别怎么实现我们的目的

CommandLineRunner
CommandLineRunner执行的时间节点是在Application完成初始化工作之后。

CommandLineRunner在有多个实现的时候,可以使用@order注解指定执行先后顺序。、

使用方法:实现CommandLineRunner接口,并重写run方法,run方法里写我们的初始化操作。

示例:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;


@Component
public class InitTest02 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("========CommandLineRunner");
    }
}

ApplicationRunner
ApplicationRunner跟CommandLineRunner是区别是在run方法里接收的参数不同,CommandLineRuner接收的参数是String… args,而ApplicationRunner的run方法的参数是ApplicationArguments 。

实现ApplicationRunner接口,并重写run方法,run方法里写我们的初始化操作。

示例:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;


@Component
public class InitTest01 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("=======ApplicationRunner");
    }
}

@PostConstruct
@PostConstruct是在对象加载完之后执行。

使用@PostConstruct注解再自己写的方法上,方法内写初始化逻辑

示例:

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


@Component
public class InitTest03 {

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

三者区别
三者都可以实现项目启动前的一些初始化操作,唯一不同的是初始化的时间不同。

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

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

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

http://www.lryc.cn/news/11561.html

相关文章:

  • 详解JavaScript的形参,实参以及传参
  • Vue中的diff算法
  • 【面试题】前端春招第二面
  • Pytorch 基础之张量数据类型
  • Java 基础面试题——常见类
  • Windows 系统从零配置 Python 环境,安装CUDA、CUDNN、PyTorch 详细教程
  • [REDIS]redis的一些配置文件
  • Java反序列化漏洞——CommonsCollections4.0版本—CC2、CC4
  • 下载网上压缩包(包含多行json)并将其转换为字典的解决方案
  • 【郭东白架构课 模块一:生存法则】11|法则五:架构师为什么要关注技术体系的外部适应性?
  • Mindspore安装
  • C++010-C++嵌套循环
  • 设计模式之迭代器模式与命令模式详解和应用
  • 【QA】[Vue/复选框全选] v-model绑定每一项的赋初值问题
  • python基于django+vue微信小程序的校园二手闲置物品交易
  • 设计模式之观察者模式
  • Java Lambda表达式
  • 【1237. 找出给定方程的正整数解】
  • java基础学习 day41(继承中成员变量和成员方法的访问特点,方法的重写)
  • 【c语言进阶】深度剖析整形数据
  • 【信息系统项目管理师】项目管理十大知识领域记忆敲出(采购风险沟通干系人)
  • [LeetCode 1237]找出给定方程的正整数解
  • 6.2 构建 RESTful 应用接口
  • 20230218英语学习
  • Linux单一服务管理systemctl
  • 【GStreamer 】 TX1中CPU和GPU解码显示海康相机RTSP流
  • 匿名内部类、Lambda表达式、方法引用对比分析
  • ESXi主机CVE-2021-21972漏洞复现安全处置建议
  • 研报精选230217
  • c++11 标准模板(STL)(std::unordered_set)(一)