SpringBoot启动初始化配置之ApplicationRunner

问题

最近需要在Spring Boot启动的时候,需要初始化第三方SDK配置,才能使用自己这个Spring Boot服务。

解决思路

使用Spring的ApplicationRunner进行初始化第三方SDK配置。Spring还有另外一个初始化接口CommandLineRunner,这里选择ApplicationRunner。

步骤

CustomApplicationRunner.java

java 复制代码
package com.xxx.init;

import com.xxx.XxxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class CustomApplicationRunner implements ApplicationRunner {
    @Value("classpath:xxx_client_config.properties")
    private Resource resource;
    @Override
    public void run(ApplicationArguments args) {
        try {
            if (XxxUtil.getInstance().init(resource.getInputStream())){
                log.info("xxx SDK 初始化成功");
            } else {
                log.error("xxxx SDK 初始化失败");
            }
        } catch (IOException e) {
            log.error("xxx SDK 初始化失败", e);
        }
    }
}

创建好这个ApplicationRunner实现类之后,然后,再启动Spring,Spring就会去初始化这个配置了。

参考

相关推荐
木易 士心12 小时前
服务器构建指南:从选型、部署到高可用架构详解
运维·服务器·后端·架构
卷无止境12 小时前
从源码到货架:拆解 Python 打包发布的核心逻辑
后端·python
mldong13 小时前
为什么在 Flowable 时代还要写一个轻量工作流引擎
后端
Sam_Deep_Thinking13 小时前
用Java 17从0到1写一个mini版RPC,理解远程调用的本质
java·面试·rpc·程序员·系统架构
敲代码的嘎仔13 小时前
从零搭建微服务:Spring Cloud Alibaba 全家桶踩坑实录(Nacos + OpenFeign + Gateway + Sentinel)
java·spring boot·spring·spring cloud·微服务·gateway·sentinel
程序员爱钓鱼13 小时前
Rust 所有权 Ownership 详解:理解内存安全的核心机制
前端·后端·rust
JaguarJack13 小时前
PHP 引用计数机制深度解析
后端·php·服务端
一条泥憨鱼14 小时前
苍穹外卖【day7| 对购物车进行操作】
java·后端·mysql·苍穹外卖
陈随易1 天前
FFmpeg 9.0 发布,代号 Lei,音视频处理再升级
前端·后端·程序员
IT界的老黄牛1 天前
Spring Boot 的 `/actuator/health` 不是免费的:健康检查打爆连接池的反面教材
spring boot·hikaricp·actuator·健康检查·线上排障·架构反模式