springboot 加载不到外部config中的配置文件

文章讨论了在SpringBoot项目中,如何正确读取外部配置文件redis.yml的问题。当使用getResource方法时,默认读取到的是jar包内的配置。解决方案包括修改代码路径为file:config/redis.yml或者在打包时设置layout为ZIP,通过-Dloader.path指定配置文件路径。然而,后者需要MANIFEST.MF中的Main-Class为PropertiesLauncher才生效。
摘要由CSDN通过智能技术生成

目录结构:

config

        application.properties

        redis.yml

xxxx.jar

项目中使用getResouce方式获取redis.yml。发现读取到的是jar包内的配置。

 URL resource = RedissonConfig.class.getClassLoader().getResource("redis.yml");

尝试方案:

1、修改代码,有效

URL resource = RedissonConfig.class.getClassLoader().getResource("file:config/redis.yml");

2、不修改代码,启动脚本中增加 -Dloader.path=${BASE_DIR}/config,无效 。

排查最后发现是springboot打包的方式不对。

最开始的pom.xml

<build>
        <finalName>xxxxxx</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.2</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

,修改后的配置,增加了layout

<build>
        <finalName>xxxxx</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.5.2</version>
                <configuration>
                    <layout>ZIP</layout>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

第一种方式生成的jar包里面MANIFEST.MF的Main-Class是JarLauncher

第二种方式生成的jar包里面MANIFEST.MF的Main-Class是PropertiesLauncher

使用-Dloader.path需要在打包的时候增加<layout>ZIP</layout>,不指定的话-Dloader.path不生效

参考:SpringBoot 打包插件spring-boot-maven-plugin打包机制及内部结构分析_build-jdk-spec_Archie_java的博客-CSDN博客

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值