maven
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.23</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
application.yaml
server:
host: localhost
port: 8771
java code
import org.yaml.snakeyaml.Yaml;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class YamlReader {
private static Map<String, Map<String, Object>> properties;
private YamlReader() {
if (SingletonHolder.instance != null) {
throw new IllegalStateException();
}
}
/**
* use static inner class achieve singleton
*/
private static class SingletonHolder {
private static YamlReader instance = new YamlReader();
}
public static YamlReader getInstance() {
return SingletonHolder.instance;
}
//init property when class is loaded
static {
InputStream in = null;
try {
properties = new HashMap<>();
Yaml yaml = new Yaml();
in = YamlReader.class.getClassLoader().getResourceAsStream("application.yaml");
properties = yaml.loadAs(in, HashMap.class);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* get yaml property
*
* @param key
* @return
*/
public Object getValueByKey(String root, String key) {
Map<String, Object> rootProperty = properties.get(root);
return rootProperty.getOrDefault(key, "");
}
}
Junit Test code
public class YamlReaderTest {
@Test
public void testYamlReader() {
Assert.assertEquals(YamlReader.getInstance().getValueByKey("server", "host"), "localhost");
Assert.assertEquals(YamlReader.getInstance().getValueByKey("server", "port"), 8771);
}
}
本文介绍了如何在Java项目中使用Maven构建,并详细阐述了如何读取application.yaml配置文件,同时提供了具体的Java代码示例以及相应的Junit测试代码。
6676

被折叠的 条评论
为什么被折叠?



