【问题标题】:Add properties file on classpath在类路径上添加属性文件
【发布时间】: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

标签: java spring classpath


【解决方案1】:

试试

java -cp "./*;lib/*;conf" com.myapp.Test

Asterix (*) 用于查找所有 JAR,而不是类。

【讨论】:

  • 是的,额外的星号是原因。我不知道,* 用于 jar 文件,没有 * 用于非 jar 文件
  • 如果不是 .jar 文件,则路径必须是目录,并且会将所有文件添加到该目录中。这就是为什么conf/ 末尾没有通配符的原因。
【解决方案2】:

对不起,去掉“conf/”后面的星号(*)。

【讨论】: