一般情况下我们常用Enventment读取配置,读取.properties,本篇文章主要从
.properties和.yml文件来分析如何使用.也谈不上分析,直接上代码,一看就会了。如果不会yml的同学,直接看代码也能看懂了(规则是死的会用就ok)
- 首先引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
读取.properties
master.ds.url=jdbc:mysql://localhost:3306/test
master.ds.username=root
master.ds.password=root
@ConfigurationProperties(prefix = "master.ds",locations = "classpath:application.properties")
public class PropsConfig {
private String url;
private String username;
private String password;
}
读取yml
myProps: #自定义的属性和值
simpleProp: simplePropValue
arrayProps: 1,2,3,4,5
listProp1:
- name: abc
value: abcValue
- name: efg
value: efgValue
listProp2:
- config2Value1
- config2Vavlue2
mapProps:
key1: value1
key2: value2
@ConfigurationProperties(prefix="myProps") //application.yml中的myProps下的属性
public class YmlConfig {
private String simpleProp;
private String[] arrayProps;
private List<Map<String, String>> listProp1 = new ArrayList<>(); //接收prop1里面的属性值
private List<String> listProp2 = new ArrayList<>(); //接收prop2里面的属性值
private Map<String, String> mapProps = new HashMap<>(); //接收prop1里面的属性值