springboot 读取外部自定义配置文件

文章介绍了如何在Springboot应用中使用JSONHelperUtil工具类来动态读取并处理外部JSON配置文件,无须重启应用。当配置文件不在同级目录时,工具类会尝试从config子目录或类路径下查找。文章还提到了工程和部署目录结构,以及在瘦包部署情况下,如何通过启动脚本确保能找到配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


前言

springboot 修改外部自定义配置文件,无需重启。

一、JSONHelperUtil

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;

import java.io.*;

@Slf4j
public class JSONHelperUtil {
    
    /**
     * 通过文件名获取获取json格式字符串,
     *
     * @param filename 文件存放路径与配置文件路径规范一致
     * @return ResolveJsonFileToString
     * @throws
     */
    public static String ResolveJsonFileToString(String filename) {
        
        BufferedReader br;
        String result;
        try {
            br = new BufferedReader(new InputStreamReader(getResFileStream(filename), "UTF-8"));
            StringBuffer message = new StringBuffer();
            String line;
            while ((line = br.readLine()) != null) {
                message.append(line);
            }
            if (br != null) {
                br.close();
            }
            String defaultString = message.toString();
//            result = defaultString.replace("\r\n", "").replaceAll(" +", "");
            //暂时不去空格(时间字符串中应该有空格)
            result = defaultString.replace("\r\n", "");
        } catch (IOException e) {
            try {
                ClassLoader classloader = Thread.currentThread().getContextClassLoader();
                InputStream in = classloader.getResourceAsStream(filename);
                br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuffer message = new StringBuffer();
                String line;
                while ((line = br.readLine()) != null) {
                    message.append(line);
                }
                if (br != null) {
                    br.close();
                }
                if (in != null) {
                    in.close();
                }
                String defaultString = message.toString();
                result = defaultString.replace("\r\n", "").replaceAll(" +", "");
            } catch (Exception e1) {
                throw new RuntimeException("没有找到文件");
            }
            
        }
        
        return result;
    }
    
    
    private static File getResFile(String filename) throws FileNotFoundException {
        File file = new File(filename);
        // 如果同级目录没有,则去config下面找
        // 此处可以自定义目录结构或多层级扩展
        if (!file.exists()) {
            log.debug("不在同级目录,进入config目录查找");
            file = new File("config/" + filename);
        }
        //config目录下还是找不到,那就直接用classpath下的
        Resource resource = new FileSystemResource(file);
        if (!resource.exists()) {
            log.debug("不在config目录,进入classpath目录查找");
            file = ResourceUtils.getFile("classpath:" + filename);
        }
        return file;
    }
    
    /**
     * 通过文件名获取classpath路径下的文件流
     *
     * @param
     * @return
     * @throws
     */
    private static FileInputStream getResFileStream(String filename) throws FileNotFoundException {
        FileInputStream fin;
        File file = getResFile(filename);
        log.info("getResFile path={}", file);
        fin = new FileInputStream(file);
        return fin;
    }
    
}

二、工程目录结构

在这里插入图片描述

三、部署目录结构

将config和部署包放在同一目录即可。此时修改config内的文件即时生效,无需重启项目。
|-config
|-部署包.jar

四、脚本启动找不到文件

当我们的部署包是瘦包部署形式时
|-启动脚本文件夹
|-公共lib
|-部署包.jar(瘦包)、config
此时我们的启动脚本通常要指定可执行jar的相对路径类似-jar ${JAR_PATH}/${JAR_NAME} ${MAIN_CLASS} ,那么此时我们需要在启动脚本添加cd到config所在文件夹,这样才可以读取到config中的文件

source /etc/profile  && cd /service/application  &&  nohup java ${JVM} ${APPLICATION_CONFIG} -Dlog4j2.formatMsgNoLookups=true -Dloader.path=../lib  -Dspring.profiles.active=${profiles}  -jar ${JAR_PATH}/${JAR_NAME} ${MAIN_CLASS} 1>/dev/null 2>&1 &

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr-Wanter

感谢大佬

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值