java 在类路径上添加属性文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34857705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:27:46  来源:igfitidea点击:

Add properties file on classpath

javaspringclasspath

提问by Michal

I am building a Spring standalone application which is based on Spring Boot. I want this application to read its properties from a property file which is outside of jar file in a separate directory. The structure of the built application looks like this

我正在构建一个基于 Spring Boot 的 Spring 独立应用程序。我希望这个应用程序从一个单独目录中的 jar 文件之外的属性文件中读取它的属性。构建的应用程序的结构如下所示

testApplication
├── test-1.0-SNAPSHOT.jar
├── lib
│   └── <dependencies are here>
└── conf
    └── application.properties

I want to load the application.properties file on classpath, so I am able to read in my application. Is it possible? Because when I run my jar file like this (on Windows):

我想在类路径上加载 application.properties 文件,以便我能够在我的应用程序中读取。是否可以?因为当我像这样运行我的 jar 文件时(在 Windows 上):

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

I get following exeption:

我得到以下例外:

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)

I try to read the file from application by this Class annotation:

我尝试通过此类注释从应用程序读取文件:

@PropertySource("classpath:application.properties")

Java documentation does not mention, that a non-jar files can be loaded on classpath, but if this application.properties is in the jar file test-1.0-SNAPSHOT.jar, then it can be accessed by this way.

Java 文档没有提到可以在classpath 上加载非jar 文件,但是如果这个application.properties 在jar 文件test-1.0-SNAPSHOT.jar 中,则可以通过这种方式访问​​它。

Is it possible to put external non-jar file on classpath? I know I don't necessarily have the file on classpath, I can access it by different ways but still I am curious if it is possible.

是否可以将外部非 jar 文件放在类路径上?我知道我不一定在类路径上有这个文件,我可以通过不同的方式访问它,但我仍然很好奇是否可能。

回答by clovish

Try

尝试

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

Asterix (*) is used to find all JARs not classes.

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

回答by eg04lt3r

Sorry, remove asteriks(*) after "conf/".

抱歉,删除“conf/”后的星号(*)。