0

I have a dynamic application.yml file and I would like to use nested lists and maps.

I know that it doesn't work out of the box, but maybe someone found a solution for it.

My goal is it that I can define something like that:

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;
Mr.Tr33
  • 768
  • 2
  • 13
  • 36

1 Answers1

0

It is not straightforward. Let's assume that below is the configuration that you want:

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

Next, you have to create a configuration class

@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;
        }
    }
}

And then use it wherever appropriate

@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());
        }
    }

}
zeagord
  • 2,087
  • 1
  • 14
  • 24