SpringBoot 官方文档示例:(28)通过application.properties给List对象和Map对象注入属性

一、对于List对象,如果在application.properties中配置了多次,直接是后边的配置替代前边的配置,不会进行合并。
例如
配置类:

package cn.edu.tju.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Configuration
@ConfigurationProperties(prefix = "my.test")
public class AppConfig4 {
    private List<String> nameList;




    public List<String> getNameList() {
        return nameList;
    }

    public void setNameList(List<String> nameList) {
        this.nameList = nameList;
    }
}

application.properties:

my.test.name_list[0]=my name 0
my.test.name_list[1]=my name 1
my.test.name_list[2]=my name 2

#---
spring.config.activate.on-profile=prod
fullName=${app.name}web

my.test.name_list[0]=my name 0 (new one)

配置文件中两处给nameList进行了配置,下边的配置起作用,nameList最终将只有一个值: my name 0 (new one)

二、对Map,如果value为对象类型,则会对相同key的对象的属性进行的合并.
1.value的类型的定义

package cn.edu.tju.domain;

public class MyPojo {
    private String name;
    private String description;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public String toString() {
        return "MyPojo{" +
                "name='" + name + '\'' +
                ", description='" + description + '\'' +
                '}';
    }
}

2.配置类:

package cn.edu.tju.config;

import cn.edu.tju.domain.MyPojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.Map;

@Configuration
@ConfigurationProperties("my.test")
public class AppConfig5 {
    private Map<String,MyPojo> map;

    public Map<String, MyPojo> getMap() {
        return map;
    }

    public void setMap(Map<String, MyPojo> map) {
        this.map = map;
    }
}

3.application.properties的配置:

my.map.key1.name=my name 1
my.map.key1.description=my description 1


#---
spring.config.activate.on-profile=dev


my.map.key1.name=dev name 1

my.map.key2.name=dev name 2
my.map.key2.description=dev description 2

当spring.profiles.active=dev 时,则配置类中的map会包含2个key:
key1和key2,它们对应的value分别为MyPojo类的对象,
值分别为:

{"name":"dev name 1","description":"my description 1"}
{"name":"dev name 2","description":"dev description 2"}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)