如何为Spring Boot项目添加外部properties配置文件并加载到类路径?
解决方案
问题根因
- 你代码中
@PropertySource(value="classpath:test.properties")是硬编码要求从类路径下加载test.properties,你打包的jar包内没有该文件,且外部props目录默认不在JVM类路径中,所以抛出找不到文件异常。 - 你使用的
--spring.config.location、--spring.config.name参数仅对Spring Boot自动加载的默认配置(如application.properties)生效,对@PropertySource手动指定的配置文件不生效,因此参数不生效。
可行解决方案
方案1:启动时将外部props目录加入类路径(无需修改代码)
因为@PropertySource指定了从类路径读取,直接把外部props目录加入JVM类路径即可。注意使用-jar参数时JVM会忽略-cp配置,因此需要调整启动命令:
Windows系统命令:
java -cp "I:\Code\my-project\props;I:\Code\my-project\target\test.jar" org.springframework.boot.loader.JarLauncher
Linux/Mac系统命令:
java -cp "/I/Code/my-project/props:/I/Code/my-project/target/test.jar" org.springframework.boot.loader.JarLauncher
方案2:修改@PropertySource支持外部路径配置
修改配置类的@PropertySource注解,用占位符支持动态传入配置文件路径:
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; @Configuration @PropertySource(value = "${test.config.path:classpath:test.properties}") public class TestConfiguration { }
启动时添加参数指定外部文件路径即可:
java -jar target\test.jar --test.config.path=file:I:\Code\my-project\props\test.properties
方案3:删除@PropertySource注解,使用Spring Boot默认配置加载逻辑
删除@PropertySource注解后,Spring Boot会自动加载你指定的配置文件,你之前写的启动命令就可以正常生效:
import org.springframework.context.annotation.Configuration; @Configuration public class TestConfiguration { }
启动命令和你之前写的一致即可:
java -jar target\test.jar --spring.config.name=test --spring.config.location=file:I:\Code\my-project\props\
内容的提问来源于stack exchange,提问作者JGleason
相关产品推荐
相关产品推荐

