如何从Maven Java项目加载外部属性文件 [英] How to load an external properties file from a maven java project
问题描述
我有一个Maven Java项目,在src/main/resources目录中有一个属性文件.我已经打包了jar,而jar中没有属性文件,因此可以将其部署到具有不同设置的不同环境中,但是单元测试失败
I have a maven java project, with a properties file in the src/main/resources directory. I've packaged the jar without the properties file in the jar, so it can be deployed to different environments with different settings, but the unit tests are failing
项目结构为
Properties Application Project
|-- pom.xml
`-- src
|-- main
|-- java
| `-- java classes
|-- resources
| `-- myProps.properties
`-- target
|--properties-app.jar
myProps.properties
值已加载到此文件中
public class MyProperties {
private Properties myProperties;
public MyProperties() {
File file = new File("./myProps.properties");
try {
myProperties = new Properties();
FileInputStream myPropertiesInputStream = new FileInputStream(file);
myProperties.load(myPropertiesInputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public Properties getPropertyValue() {
return myProperties.getProperty("value");
}
}
单元测试如下
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class MyPropertiesTest {
private MyProperties myProperties;
@Before
public void setup() {
myProperties = new MyProperties();
}
@Test
public void testMyProperties() {
assertNotNull(myProperties.getPropertyValue());
}
}
我应该使用什么来从目标目录加载属性文件,以便可以从命令行成功构建它?
What should I use to load the properties file from the target directory so I can build it successfully from the command line?
推荐答案
我希望您正在使用maven jar插件.如果是这样,请在jar-plugin中使用此配置
I hope you are using maven jar plugin. If so use this configuration inside jar-plugin
<configuration>
<archive>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>
然后jar将从jar文件的根目录中获取属性文件.
Then the jar will take the properties file from root directory of jar file.
这篇关于如何从Maven Java项目加载外部属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!