SpringBoot讀取兩種格式的配置文件

通常狀況下咱們經常使用Enventment讀取配置,讀取.properties,本篇文章主要從
.properties和.yml文件來分析如何使用.也談不上分析,直接上代碼,一看就會了。若是不會yml的同窗,直接看代碼也能看懂了(規則是死的會用就ok)mysql

  • 首先引入依賴
<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=rootspring

@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裏面的屬性值
相關文章
相關標籤/搜索