编码技巧——Springboot工程打jar包后启动时读取jar包外的资源文件

1. 背景

基于springboot的工程项目,使用jar方式打包,在打包时将资源文件和配置文件(springboot内置的application.properties/application.yml)单独打出来,方便修改配置而不需要重新编译打jar包;

当然,如果不将配置文件单独打包出来的话,所有的resource目录下的配置文件都会被默认打入jar、包内部,读取路径统一变成:file/:jar包所在目录/xxx-jar.jar!/BOOT-INF/classes!/,如果想修改配置那就只能重新编译打包了;

其实,当下更好的方式是使用配置中心来下发动态配置,如nacos、apollo这类成熟的配置中心中间件,但是本次开发的系统未引入相关的配置中心中间件,采用单机部署,准备快速简单做,所以就准备使用离线的方式来实现配置能实时从配置文件修改;

我们知道,springboot会默认在jar包同目录下的/config或者根目录中找application.yml和application.properties文件(可能是处于安全考虑);

那么怎么让springboot也能读取到我们自定义的配置文件呢?

2. 方案

方案1:把业务配置写入application.yml/application.properties

理论上可以做到修改配置无需重新编译发版,但是这样做也存在缺点——application.yml / application.properties文件只会在springboot启动时加载一次,若修改了业务配置,则需要重启服务,无法实时生效

方案2:以读取文件的方式来实时加载配置文件

例如:我们在刚开始学习java io的时候写过过读取系统某目录下txt文件的代码,当修改txt文件内容时,java代码中读取到的文件内容是会实时变化的,那么我们现在的问题就是——怎么指定配置文件的路径

解决:通过查阅资料,很多帖子都没提到重点只是提了下怎么读取文件,没提到重点,最后终于找到了对应的解决方案——使用 FileSystemResource 类加载资源文件;

原因:在使用springboot的插件打成jar包后,此时启动路径与idea中的路径发生变化,资源文件描述发生变化,但是user.dir并没有发生变化;而FileSystemResouce本来就是相对于启动路径来寻找文件的,刚好和我们的需求匹配;


3. 测试

(1)打包时指定将配置文件helpDocConfig.json打到跟jar包平级的config/biz/目录下;

(2)输出的tar包,解压后目录如下

(3)启动jar包,调用测试接口,查看到此时的输出的内容

(4)修改文件,不重启工程,再次调用测试接口,看到此时输出了我们刚修改后的内容,说明使用FileSystemResource实时读取到了离线配置文件;

4. 代码

你们想要的就是这个吧,不废话,上源码;

    private void testExternalSrc() {
        String fileName = "config/biz/helpDocConfig.json";
        // 相对工作目录下面即user.dir
        FileSystemResource fileSystemResource = new FileSystemResource(fileName);
        File file = fileSystemResource.getFile();
        String absolutePath = file.getAbsolutePath();
        System.out.println("fileName:" + fileName + ",absolutePath:" + absolutePath);
        if (file.exists()) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader newBufferedReader = Files.newBufferedReader(file.toPath());) {
                String readLine = null;

                while ((readLine = newBufferedReader.readLine()) != null) {
                    sb.append(readLine);
                    System.out.println(readLine);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("text:" + sb);
        }
    }

这里再附一下普通的读取jar包中的resource目录下配置文件的代码,因为是打jar包,写法跟本地运行存在点差异:

示例(1)

@Slf4j
@Component
public class PropertyUtils {

    @Resource
    private ResourceLoader resourceLoader;

    public Properties getProperty(String fileName) {
        try {
            InputStream in = resourceLoader.getResource(fileName).getInputStream();
            Properties properties = new Properties();
            properties.load(in);
            in.close();
            return properties;
        } catch (Exception e) {
            log.error("读取文件内容到Properties失败! [fileName={}]", fileName, e);
            throw new RuntimeException("读取文件内容到Properties失败! [fileName=" + fileName + "]");
        }
    }

    public String getProperty2String(String fileName) {
        try {
            InputStream in = resourceLoader.getResource(fileName).getInputStream();
            String content = IOUtils.toString(in, StandardCharsets.UTF_8);
            in.close();
            return content;
        } catch (Exception e) {
            log.error("读取文件内容到String失败! [fileName={}]", fileName, e);
            throw new RuntimeException("读取文件内容到String失败! [fileName=" + fileName + "]");
        }
    }
}

示例(2)

@Slf4j
public class FileLoaderUtils {

    /**
     * 读文件文本到String 根目录为resource
     *
     * @param fileName
     * @return
     */
    public static String loadFile2String(String fileName) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(fileName);
        if (url == null) {
            log.error("Cannot_locate_" + fileName + "_as_a_classpath_resource.");
            throw new RuntimeException("Cannot_locate_" + fileName + "_as_a_classpath_resource.");
        }
        try {
            return IOUtils.toString(url, StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("读取文件内容为String失败! [fileName={}]", fileName, e);
            throw new RuntimeException("读取文件内容为String失败! [fileName=" + fileName + "]");
        }
    }

    /**
     * 读文件文本到Property 根目录为resource
     *
     * @param fileName
     * @return
     */
    public static Properties loadFile2Property(String fileName) {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream in = loader.getResourceAsStream(fileName);
        Properties properties = new Properties();
        try {
            properties.load(in);
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
            log.error("读取文件内容到Properties失败! [fileName={}]", fileName, e);
            throw new RuntimeException("读取文件内容到Properties失败! [fileName=" + fileName + "]");
        }
        return properties;
    }

}

补充

由于频繁读取系统文件会占用IO资源,可以将上述代码封装,改为定时刷新+懒加载方式,将离线配置文件的内容刷到本地缓存或Redis中,来减小服务器IO压力;

当然——最好的方案还是使用专业的配置中心中间件来实现配置的实时修改,专业的人干专业的事

参考:

springboot打成jar运行,无法读取配置文件或静态资源的问题

SpringBoot:加载和读取jar包外面的资源文件-华为云开发者联盟

  • 19
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值