天天看点

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) {    
 …… 
}