1. 配置List和Map
properties:
第一种写法:
<!--list配置-->
ababa.myList = 1,2,n
第二种写法
ababa.myMap ={'k1':'李四','k2':'张三'}
第二种写法
<!--list配置-->
ababa.myList[0]=1
ababa.myList[1]=2
ababa.myList[2]=n
<!--map配置-->
ababa.myMap.1=张三
ababa.myMap.2=李四
ababa.myMap.key=value
2. 读取配置文件
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import java.util.List;
@Getter
@Setter
@Component
@RefreshScope
@ConfigurationProperties(prefix = "ababa")
public class ImportProperties {
//第一种注入list的方法(myList名称要与配置文件保持一致而且prefix = "ababa"下一级就是它,很重要)
private List<String> myList = new ArrayList<>();
//map同理
private Map<String,Object> myMap = new HashMap<>();
/**
* 第二种注入list的方法,对应第一种list properties写法,根据逗号分开
*不需要依赖下面这些注解,简单些
* @Setter
* @Component
* ---@RefreshScope(动态刷新建议保留)
* @ConfigurationProperties(prefix = "ababa")
*/
}
@Value("#{'${ababa.myList}'.split(',')}")
private List<String> myList;
}
@Value("#{${test.mymap:{'k1':'李四','k2':'张三'}}}")
private Map<String,String> mymap;