application.properties 配置list<String>和list<实体类>

5,099 阅读2分钟

application.properties 配置list对象

背景介绍

原需求是所有城市都查 《商品住宅》类型的数据,现在有五个城市改成查《商品住宅不含保障性住房》类型的数据

思路:前端传入城市id,写一个判断,如果这个城市id属于那五个城市,我们就手动把类型改成《商品住宅不含保障性住房》,再去查数据。

现在想要配到配置文件中,或者是放到阿波罗中,这样如果下次需求又加几个城市,或者又加类型比如《写字楼》,比如我们直接改阿波罗配置就可以,不需要动代码。

List类型配置

文件配置

在application.properties文件中添加城市列表 格式:name=aaa,bbb,ccc,ddd

newhouse.deal.cityid.list =3146b167,63f76a67,35DCD8BD,94E55784,7B7C7DE8

接收方法

下面的格式一定要对,用split(',')方法拿到每个城市id放到List cityIdList

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

打印结果

System.out.println(cityIdList.toString());
//[3146b167, 63f76a67, 35DCD8BD, 94E55784, 7B7C7DE8]

List<对象>类型配置 官方文档地址

添加依赖

<dependency>
   <groupId> org.springframework.boot </groupId>
   <artifactId> spring-boot-configuration-processor </artifactId>
   <optional> true </optional>
</dependency>

文件配置

application.properties文件添加配置,这里的属性需要和实体类保持一直

newhouse.deal.index.list[0].indexId =c7b5a
newhouse.deal.index.list[0].indexName =商品住宅(不含保障性住房)>销售面积
newhouse.deal.index.list[0].indexUints =万平方米
​
newhouse.deal.index.list[1].indexId =f1ab8
newhouse.deal.index.list[1].indexName =商品住宅(不含保障性住房)>销售价格
newhouse.deal.index.list[1].indexUints =元/平方米

创建类

  • @ConfigurationProperties(prefix = "newhouse.deal.index") 这里配置前缀
  • private List list; 这里的list需要和配置文件中保持一直
/**
 * @author fanxiaofeng
 * @description: TODO
 * @since 2022/8/23
 */
@Data
@Component
@ConfigurationProperties(prefix = "newhouse.deal.index")
public class TableIndexBoList {
    private List<TableIndexBo> list;
}
@Data
public class TableIndexBo {
    private String indexId;
    
    private String indexName;
    
    private String indexUints;
​
    public TableIndexBo() {
    }
    public TableIndexBo(String indexId, String indexName, String indexUints) {
        this.indexId = indexId;
        this.indexName = indexName;
        this.indexUints = indexUints;
    }
}

打印结果

tableIndexBoList.getList().forEach(t-> System.out.println(t.toString()));
//TableIndexBo(indexId=c7b5a, indexName=商品住宅(不含保障性住房)>销售面积, indexUints=万平方米)
//TableIndexBo(indexId=f1ab8, indexName=商品住宅(不含保障性住房)>销售价格, indexUints=元/平方米)