【发布时间】:2026-02-07 02:55:02
【问题描述】:
我正在构建一个基于 Spring Boot 的 Spring 独立应用程序。我希望此应用程序从单独目录中的 jar 文件之外的属性文件中读取其属性。构建的应用程序的结构是这样的
testApplication
├── test-1.0-SNAPSHOT.jar
├── lib
│ └── <dependencies are here>
└── conf
└── application.properties
我想在类路径上加载 application.properties 文件,这样我就可以读取我的应用程序。是否可以?因为当我像这样运行我的 jar 文件时(在 Windows 上):
java -cp "./*;lib/*;conf/*" com.myapp.Test
我得到以下异常:
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.myapp.Test]; nested exception is java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist
at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:180)
...
Caused by: java.io.FileNotFoundException: class path resource [application.properties] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
我尝试通过这个 Class 注释从应用程序中读取文件:
@PropertySource("classpath:application.properties")
Java文档中没有提到可以在classpath上加载一个非jar文件,但是如果这个application.properties在jar文件test-1.0-SNAPSHOT.jar中,那么可以通过这种方式访问。
是否可以将外部非 jar 文件放在类路径中?我知道我不一定在类路径上有文件,我可以通过不同的方式访问它,但我仍然很好奇它是否可能。
【问题讨论】:
-
java -cp ".;lib;conf" com.myapp.Test