gpt4 book ai didi

java - 如何从 maven java 项目加载外部属性文件

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:45:37 25 4
gpt4 key购买 nike

我有一个 maven java 项目,在 src/main/resources 目录中有一个属性文件。我已经打包了jar,jar里面没有properties文件,所以可以部署到不同的环境,不同的设置,但是单元测试失败

项目结构是

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());

}

}

我应该使用什么从目标目录加载属性文件,以便我可以从命令行成功构建它?

最佳答案

希望您使用的是 maven jar 插件。如果是这样,请在 jar-plugin 中使用此配置

    <configuration>
<archive>
<manifestEntries>
<Class-Path>.</Class-Path>
</manifestEntries>
</archive>
</configuration>

然后jar将从jar文件的根目录中获取属性文件。

关于java - 如何从 maven java 项目加载外部属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34712885/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com