Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define complex list for application yml in spring boot?

Suppose I have this application.yml defined:

spring:
    profiles.active: development
---
spring:
    profiles: development
logging:
    level:
        org.springframework.web: DEBUG
        org.hibernate: ERROR
storage:
    RemoteStorage:
        name: "Server 1"
        user: "test"
        passwd: "test"
        host: "163.218.233.106"

    LocalStorage:
        name: "Server 2"
        user: "test2"
        passwd: "test2"
        host: "10.10.0.133"
---

The storage is a custom properties that I want it to be load like this:

@Value("${storage}")
private List<Storage> AvailableStorage = new ArrayList<>();

Apologies I am a beginner with Spring framework. What I was trying to do is to have the RestController read respective config based on the parameters provided from requests, i.e. Requests like ?storage=RemoteStorage will use the RemoteStorage config.

like image 239
user1510539 Avatar asked Oct 29 '22 21:10

user1510539


1 Answers

@Value annotation will not load list or map type of properties. For this you have to define a class with @ConfigurationProperties annotation like below.

import java.util.List;
import java.util.Map;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix ="storage")
public class MyProps {

private List<String> listProp;
private Map<String, String> mapProp;

public List<String> getListProp() {
    return listProp;
}
public void setListProp(List<String> listProp) {
    this.listProp = listProp;
}
public Map<String, String> getMapProp() {
    return mapProp;
}
public void setMapProp(Map<String, String> mapProp) {
    this.mapProp = mapProp;
   }
}

And below is the application.yaml file for above property configuration class.

storage:
listProp:
    - listValue1
    - listValue2
mapProp:
    key1: mapValue1
    key2: mapValue2

If you are using the application.properties file instead of .yaml file then

storage.listProp[0]=listValue1
storage.listProp[1]=listValue2
storage.mapProp.key1=mapValue1
storage.mapProp.key2=mapValue2
like image 76
abaghel Avatar answered Nov 15 '22 06:11

abaghel