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
  • 838
  • 2
  • 18
  • 42

2 Answers2

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,257
  • 3
  • 17
  • 24
0

I think, you can extend as per your requirement but this works in my code ( Spring Boot ), though its not a List but array. Also, I needed a solution which doesn't needed a specific config Java class as most of old answers are about creating a property configuration class.

my-map-property-name: "{\
         KEY1: \"[VALUE1,VALUE2]\",\  
         KEY2: \"[VALUE3]\"  \ }"


@Value("#{${my-map-property-name}}")
    private Map<String, String[]> myMap;

I tested it and you can use enum values as well for Map key and values.

Three things ,

  1. Its a json format
  2. Its a multi line json
  3. value part is double quoted

Reference SO Answer

Also, to get a List from a delimiter separated values in a String , you can call split method,

@Value("#{'${my.property:def_val}'.split(',')}")
private List<String> myValues;

where def_val is the default value of property.

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98