SoFunction
Updated on 2025-04-13

Springboot reads map and list type configuration parameters in .properties configuration file

springboot reads map and list type configuration parameters in .properties configuration file

A set of configuration parameters are stored in the file, namely map type and list type, and the configuration parameters are read through the test method.

1. Configuration file

#map The first method=zhangsan
=man
=11
=xxxxxxxx
#map The second way[name]=zhangsan
[sex]=man
[age]=11
[url]=xxxxxxxx
#list The first way[0]=apple0
[1]=apple1
[2]=apple2
#list The second way=apple0,apple1,apple2

2. Inject configuration information

@Configuration
@ConfigurationProperties(prefix = "data")
//If there is only one main configuration class file, @PropertySource can be ignored@PropertySource("classpath:")
public class PersonConfig {
 
    /**
      *
      * The map name here needs to be consistent with the parameters in it
      */
    private Map<String, String> person = new HashMap<>();
    /**
      *
      * The list name here needs to be consistent with the parameters in it
      */
    private List<String> list = new ArrayList<>();
 
 
    /**
      * Write get, set method is easy to use
      */
    public Map<String, String> getPerson() {
        return person;
    }
 
    public void setPerson(Map<String, String> person) {
         = person;
    }
 
    public List<String> getList() {
        return list;
    }
 
    public void setList(List<String> list) {
         = list;
    }
}

3. Use

    @Autowired
    private PersonConfig personConfig;
 
    @Test
    public void contextLoads() {
 
        Map<String, String> person = ();
        List<String> list = ();
        ("image:"+(person).toString());
        ("list:"+ (list).toString());
    }
 
    //Output result    image:{"sex":"man","name":"zhangsan","age":"11","url":"xxxxxxxx"}
    list:["apple0","apple1","apple2"]

Summarize

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