天天看點

SpringBoot項目讀取配置檔案資訊

第一種:@ConfigurationProperties

@ConfigurationProperties注解用于讀取指定字首的一組配置資訊并與bean綁定,具體的配置屬性會綁定到bean的成員屬性中,即字首名+成員屬性名等于配置檔案中的key。之後可以像使用其他bean一樣使用該bean并讀取配置資訊。

user:
 name: zhangsan
 sex: 男
 homeUrl: www.xxx.com      

配置檔案如上

@Component
@Data
@ConfigurationProperties(prefix = "user")
public class User {
  private String name;
  private String sex;
  private String homeUrl;
}      

當我們項目比較大配置資訊比較多的時,如果所有的配置資訊都放在一個配置檔案中,就會顯得比較臃腫且不易了解和維護。此時,我們可以按照需求将該配置檔案拆分為多個,并使用@PropertySource注解配合@Value或@ConfigurationProperties讀取指定配置檔案中的配置資訊。假設我們存儲資料連接配接資訊的配置檔案為​​jdbc.properties​​,内容如下: 

jdbc:
 account: zhangsan
 pwd: 123456      
@Component
@Data
@PropertySource(value = {"classpath:jdbc.properties"})
@ConfigurationProperties(prefix = "jdbc")
public class JdbcCfg {
  private String account;
  private String pwd;

  public void connectDb() {
    System.out.println("Database has connected, jdbc account is "
      + account + ", password is " + pwd);
  }
}      

2、通過@Value方式來讀取配置資訊

local:
  ip:
    addr: 192.168.137.220-yml      
@Value("${local.ip.addr}")
String addr;
//這裡可以設定預設值,如果沒有改配置項,給改配置項添加預設值
@Value("${local.ip.port:9000}")
String port;
@Value("${user.dir}")
String userDir;

//這玩意可以定位讀取哪個檔案

@PropertySource(value = {"classpath:jdbc.properties"})      
SpringBoot項目讀取配置檔案資訊

 第三種:PropertiesLoaderUtils讀取

ClassPathResource resource = new ClassPathResource("application.properties");  
try {    
 Properties properties = PropertiesLoaderUtils.loadProperties(resource);   
    String account = properties.getProperty("jdbc.account");        
} catch (IOException e) {    
 …… 
}