Spring使用@VALUE在YAML中使用Lists和Maps

时间:2017-10-06 09:51:54

标签: spring-boot arraylist hashmap yaml

我有一个动态的application.yml文件,我想使用嵌套列表和地图。

我知道它没有开箱即用,但也许有人找到了解决方案。

我的目标是我可以定义类似的内容:

user:
  test:
    - peter
    - willi
  test2:
    - helloA: abc
      helloA2: def
    - helloB: 123
      helloB2: 345

-

@Value("${user.test}")
private String[] names;

@Value("${user.test2}")
private List<Map> test;

1 个答案:

答案 0 :(得分:0)

这不是直截了当的。我们假设下面是您想要的配置:

user:
 test:
   -
    name: johndoe
    email: john@doe.com
   -
    name: jackdoe
    email: jackdoe

接下来,您必须创建配置类

@ConfigurationProperties(prefix = "myconfig")
public class MyConfig {
    private List<User> users;

    public MyConfig() {

    }

    public MyConfig(List<User> users) {
        this.users = users;
    }

    public void setUsers(List<User> users) {
        this.users = users;
    }

    public List<User> getUsers() {
        return users;
    }

    public static class User {
        private String name;
        private String email;
        public String getName() {
            return name;
        }

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

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
    }
}

然后在适当的地方使用它

@Configuration
@EnableConfigurationProperties(User.class)
public class ClassThatNeedsUser{

    @Autowired
    private User user;

    private Map usersMap = new HashMap();

    @Bean
    public ClassThatNeedsUser getUserList(){
        for(User user: user.getUsers()) {
            usersMap.put(user.getName(), user.getEmail());
        }
    }

}