spring yml

Last updated on September 9, 2024 am

🧙 Questions

直接读取项目中的yaml文件

☄️ Ideas

package demo.yml;

public class Dog {

    public String name;

    public Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Dog{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}
dogs:
  - { username: 'zhangsan',age: 12 }
  - { username: 'lisi',age: 13 }
  - { username: 'wangwu',age: 14 }
package demo.yml;

import org.junit.jupiter.api.Test;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class YmlTest {

    @Test
    public void parseYaml() {

        DefaultResourceLoader defaultResourceLoader = new DefaultResourceLoader();
        Resource resource = defaultResourceLoader.getResource("test.yml");
        Yaml yaml = new Yaml();
        List<Dog> dogs = new ArrayList<>();
        try {
            Map<String, List<Object>> load = yaml.load(resource.getInputStream());
            List<Object> apiList = load.get("dogs");
            if (apiList != null) {
                apiList.forEach(e -> {
                    Map<String, Object> metaApi = (Map) e;
                    Dog metaDog = new Dog();
                    metaDog.setName(String.valueOf(metaApi.get("username")));
                    metaDog.setAge(Integer.parseInt(String.valueOf(metaApi.get("age"))));
                    dogs.add(metaDog);
                });
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        dogs.forEach(e-> System.out.println(e.toString()));
    }
}

spring yml
https://ispong.isxcode.com/spring/spring/spring yml/
Author
ispong
Posted on
June 10, 2021
Licensed under