1.依赖包

		<dependency>
            <groupId>org.yaml</groupId>
            <artifactId>snakeyaml</artifactId>
            <version>1.26</version>
        </dependency>

2.application.yml文件

##### redis的配置信息
redis:
    host: 172.31.223.30
    port: 16379
    password: iflytek!

### 服务端的配置信息
server:
  shost: 10.3.16.30
  sport: 34962

3.解析yml文件

		public static void main(String[] args) {
        Yaml yaml = new Yaml();
        InputStream resourceAsStream = Constant.class.getClassLoader().getResourceAsStream("application.yml");
        Map obj = yaml.load(resourceAsStream);
        Map<String,Object> param = new HashMap<>();
        //需要注意,此类加载器只能得到它的最顶层的key的值
        Map<String,Object> params= (Map) obj.get("redis");
        param.putAll(params);
        System.out.println("params = " + params );
        Map<String,Object> params2= (Map) obj.get("server");
        param.putAll(params2);
        System.out.println("params2 = " + params2 );
        System.out.println("param = " + param );
    }

4.打印结果

params = {host=172.31.223.30, port=16379, password=iflytek!}
params2 = {shost=10.3.16.30, sport=34962}
param = {host=172.31.223.30, password=iflytek!, port=16379, sport=34962, shost=10.3.16.30}
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐