java如何讀取yaml配置文件
更新時間:2024年01月15日 09:21:33 作者:qzqanlhy1314
這篇文章主要介紹了java如何讀取yaml配置文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
java讀取yaml配置文件
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); } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳解java封裝返回結(jié)果與RestControllerAdvice注解
這篇文章主要為大家介紹了java封裝返回結(jié)果與RestControllerAdvice注解實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09java階乘計算獲得結(jié)果末尾0的個數(shù)代碼實現(xiàn)
今天偶然看到一個要求,求1000~10000之間的數(shù)n的階乘并計算所得的數(shù)n!末尾有多少個0?要求: 不計算 只要得到末尾有多少個0就可以了,看下面的代碼吧2013-12-12SpringBoot @ConfigurationProperties使用詳解
這篇文章主要介紹了SpringBoot @ConfigurationProperties使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02MyBatis的@SelectProvider注解構(gòu)建動態(tài)SQL方式
這篇文章主要介紹了MyBatis的@SelectProvider注解構(gòu)建動態(tài)SQL方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-08-08