SoFunction
Updated on 2025-04-13

How to configure nested map and list parameters in springboot

A set of configuration parameters are stored in the .properties file, namely map type and list type, including various nested complex types such as map<String,List<String>>, List<Map<String,String>>, map<String,List<Pojo>>, List<Map<String,Pojo>>, etc., to do testing methods and read configuration parameters.

1. Primary version --Map<String,String> and List<String>

1.1. Add the following parameters to the configuration file

#map The first method.key01=java
.key02=hadoop
.key03=flink
#map The second method (recommended)[key01]=java
[key02]=hadoop
[key03]=flink
#list The first way[0]=apple0
[1]=apple1
[2]=apple2
#list The second method (recommended)=apple0,apple1,apple2

1.2. Write the MapListConfig class to read configuration information

package ;

import ;
import ;
import ;

import ;
import ;
import ;
import ;

@Configuration
@ConfigurationProperties(prefix = "data")
//If there is only one main configuration class file, @PropertySource can be ignored@PropertySource("classpath:")
public class MapListConfig {
    /**
      *
      * The map name here needs to be consistent with the parameters in it
      */
    private Map&lt;String, String&gt; mapConfig = new HashMap&lt;&gt;();
    /**
      *
      * The list name here needs to be consistent with the parameters in it
      */
    private List&lt;String&gt; listConfig = new ArrayList&lt;&gt;();

    /**
      * Write get, set method is easy to use
      */
    public Map&lt;String, String&gt; getMapConfig() {        return mapConfig;    }
    public void setMapConfig(Map&lt;String, String&gt; mapConfig) {         = mapConfig;    }
    public List&lt;String&gt; getListConfig() {        return listConfig;    }
    public void setListConfig(List&lt;String&gt; listConfig) {         = listConfig;    }
}

1.3. Test type test

package ;


@RunWith()
@SpringBootTest
public class SpringbootTest {
    @Autowired
    private MapListConfig mapListConfig;

    @Test
    public void mapListTest() {
        Map<String, String> map = ();

        List<String> list = ();

        ("Map<String, String>:  "+(map));
        ("List<String>:  "+ (list));
    }
}

//Output result

Map<String, String>: {"key03":"flink","key02":"hadoop","key01":"java"}
List<String>: ["apple0","apple1","apple2"]

Add another automatic injection:

@Value("#{'${}'.split(',')}")
private List<String> list;

2. Intermediate version--map<String,List<String>> and List<Map<String,String>>

2.1. Add the following parameters to the configuration file

#map-- map<String,List<String>>
.key01[0]=java
.key01[1]=hadoop
.key01[2]=flink
.key02[0]=pyhthon
.key02[1]=c++
.key02[2]=scala

#list -- List<Map<String,String>>
[0].key01=apple0
[0].key02=apple1
[1].key01=apple3
[1].value02=apple4

2.2. Write the MapListConfig02 class to read configuration information

package ;

@Configuration
@ConfigurationProperties(prefix = "data01")
//If there is only one main configuration class file, @PropertySource can be ignored@PropertySource("classpath:")
public class MapListConfig02 {
    /**
      *
      * The map name here needs to be consistent with the parameters in it
      */
    private Map&lt;String,List&lt;String&gt;&gt; mapList = new HashMap&lt;&gt;();
    /**
      *
      * The list name here needs to be consistent with the parameters in it
      */
    private List&lt;Map&lt;String,String&gt;&gt; listMap = new ArrayList&lt;&gt;();

    /**
      * Write get, set method is easy to use
      */
    public Map&lt;String, List&lt;String&gt;&gt; getMapList() {        return mapList;    }
    public void setMapList(Map&lt;String, List&lt;String&gt;&gt; mapList) {         = mapList;    }
    public List&lt;Map&lt;String, String&gt;&gt; getListMap() {        return listMap;    }
    public void setListMap(List&lt;Map&lt;String, String&gt;&gt; listMap) {         = listMap;    }
}

2.3. Test type test

@RunWith()
@SpringBootTest
public class SpringbootTest {
    @Autowired
    private MapListConfig mapListConfig;

    @Autowired
    private MapListConfig02 mapListConfig02;


    @Test
    public void mapListTest02() {
        Map<String, List<String>> mapList = ();

        List<Map<String, String>> listMap = ();

        ("Map<String, List<String>>:  "+(mapList));
        ("List<Map<String, String>>:  "+ (listMap));
    }
}

//Output result
Map<String, List<String>>: {"key02":["pyhthon","c++","scala"],"key01":["java","hadoop","flink"]}
List<Map<String, String>>: [{"key01":"apple0","key02":"apple1"},{"key01":"apple3","value02":"apple4"}]

3. Advanced version--Map<String,List<Pojo>> and List<Map<String,Pojo>>

3.1. Add the following parameters to the configuration file

#The third type#map-- map&lt;String,List&lt;POJO&gt;&gt;
.key01[0].name=zhangsan
.key01[0].sex=male
.key01[0].age=30
.key01[1].name=lisi
.key01[1].sex=female
.key01[1].age=33
.key02[0].name=wangwu
.key02[0].sex=male
.key02[0].age=35

#list -- List&lt;Map&lt;String,POJO&gt;&gt;
[0].key01[name]=zhangsan
[0].key01[sex]=male
[0].key01[age]=17
[1].key01[name]=lisi
[1].key01[sex]=female
[1].key01[age]=18

3.2. Write the MapListConfig03 class to read configuration information

package ;

@Configuration
@ConfigurationProperties(prefix = "data02")
//If there is only one main configuration class file, @PropertySource can be ignored@PropertySource("classpath:")
public class MapListConfig03 {
    /**
      *
      * The map name here needs to be consistent with the parameters in it
      */
    private Map&lt;String,List&lt;Person&gt;&gt; mapList = new HashMap&lt;&gt;();
    /**
      *
      * The list name here needs to be consistent with the parameters in it
      */
    private List&lt;Map&lt;String,Person&gt;&gt; listMap = new ArrayList&lt;&gt;();

    /**
      * Write get, set method is easy to use
      */
    public Map&lt;String, List&lt;Person&gt;&gt; getMapList() {        return mapList;    }
    public void setMapList(Map&lt;String, List&lt;Person&gt;&gt; mapList) {         = mapList;    }
    public List&lt;Map&lt;String, Person&gt;&gt; getListMap() {        return listMap;    }
    public void setListMap(List&lt;Map&lt;String, Person&gt;&gt; listMap) {         = listMap;    }
}

3.3. Test type test

@RunWith()
@SpringBootTest
public class SpringbootTest {
    @Autowired
    private MapListConfig mapListConfig;

    @Autowired
    private MapListConfig02 mapListConfig02;

    @Autowired
    private MapListConfig03 mapListConfig03;

    @Autowired private Environment env;

    @Test
    public void mapListTest03() {
        Map<String, List<Person>> mapList = ();

        List<Map<String, Person>> listMap = ();

        ("Map<String, List<Person>>:  "+(mapList));
        ("List<Map<String, Person>:  "+ (listMap));
    }
}

//Output result
Map<String, List<Person>>: {"key02":[{"age":35,"name":"wangwu","sex":"male"}],"key01":[{"age":30,"name":"zhangsan","sex":"male"},{"age":33,"name":"lisi","sex":"female"}]}
List<Map<String, Person>: [{"key01":{"age":17,"name":"zhangsan","sex":"male"}},{"key01":{"age":18,"name":"lisi","sex":"female"}}]

3.4、FAQ: Field required a single bean, but 2 were found

Solution: Add @Primary to tell spring which main implementation class to use when initializing.

(1)@Autowired

@Autowired's annotations provided by Spring require importing packages; only injection is performed according to byType.

The @Autowired annotation is to assemble dependent objects by type (byType). By default, it requires dependent objects to exist. If null values ​​are allowed, its required attribute can be set to false. If we want to assemble by name (byName), we can combine@QualifierUse annotations together. as follows:

(2)@Resource

@Resource is automatically injected according to ByName by default, provided by J2EE, and requires importing packages. @Resource has two important properties: name and type, while Spring parses the name attribute of the @Resource annotation to the name of the bean, and the type attribute resolves to the type of the bean.

Four and four ways to get configuration

4.1. @ConfigurationProperties method +(prefix = "data")

Suitable for Map and List configurations, need to be prefixed ‘prefix

4.2. Use @Value annotation method

Applicable to single key=value

4.3. Use the built-in environment

Applicable to single key=value

import ;
@Autowired private Environment env;

...

("type", (""));
("title", new String(("").getBytes("ISO-8859-1"), "UTF-8")); // Solve Chinese garbled code

4.4. Use the built-in environment

  • Method 1:Properties properties = ("");
  • Method 2:Since the configuration file is generally global at the same time, it can be obtained when the monitoring process of the PropertiesListener is started. Can avoid loading every time the method is called

1. Write a PropertiesListener class for monitoring configuration files

Whenever ApplicationContext publishes ApplicationEvent, the ApplicationListener Bean will be automatically triggered by java

public class PropertiesListener implements ApplicationListener<ApplicationStartedEvent> {
    private String propertyFileName;
    public PropertiesListener(String propertyFileName) {
         = propertyFileName;
    }
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        (propertyFileName);
    }
}

2. Write a configuration file to load the class PropertiesListenerConfigweb

public class PropertiesListenerConfig {
    public static Map&lt;String, String&gt; propertiesMap = new HashMap&lt;&gt;();
    
    private static void processProperties(Properties props) throws BeansException {
        propertiesMap = new HashMap&lt;String, String&gt;();
        for (Object key : ()) {
            String keyStr = ();
            try {
                // The default encoding of PropertiesLoaderUtils is ISO-8859-1, transcoding it here                (keyStr, new String((keyStr).getBytes("ISO-8859-1"), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                ();
            } catch ( e) {
                ();
            }
        }
    }

    public static void loadAllProperties(String propertyFileName) {
        try {
            Properties properties = (propertyFileName);
            processProperties(properties);
        } catch (IOException e) {
            ();
        }
    }

    public static String getProperty(String name) {
        return (name).toString();
    }

    public static Map&lt;String, String&gt; getAllProperty() {
        return propertiesMap;
    }
}

3. Add listening spring on the springboot startup class

public static ApplicationContext applicationContext;

      public static void main(String[] args) {
		  SpringApplication application = new SpringApplication();
	       // The fourth method: register the listener          (new PropertiesListener(""));
          applicationContext =  (args);
     }
 }

4. Call SQL through ();

Map<String, String> allProperty = ();

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.