使用Spring Boot時,可將變量的值寫在properties或yml配置文件中,通過讀取配置文件中的鍵值對獲取,方便靈活修改服務配置。Spring Boot讀取配置值的方式很多,常見的有3種:使用@Value註解、使用@ConfigurationProperties註解和通過Environment對象獲取。
下面將通過代碼示例依次介紹3種方法,properties文件中的配置如下:
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=123456
spring.cache.redis.time-to-live=600000
person.name=Tom
person.age=30
方法1 使用@Value註解
創建變量時,加上@Value註解,即可直接讀取配置文件中相應鍵值,爲該變量賦值。示例如下:
@Value("${spring.cache.redis.time-to-live}")
private Long timeToLive;
此方式使用時有一定風險,若配置項的類型不是String,則配置文件中該項的值不能爲空。因爲程序讀取配置文件中值的類型爲String,賦值前再轉換爲變量定義的類型,此時可能會出現異常。例如在本文示例中,若配置文件中未賦值,則空值轉爲Long類型會出現空指針異常。
方法2 使用@ConfigurationProperties註解
創建實體類時,加上使用@ConfigurationProperties註解,可讀取配置文件中符合約束條件的鍵值對,爲類屬性賦值。示例如下:
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
用@ConfigurationProperties註解將前綴爲person的配置項的值取出,賦予Person類中字段名相同的屬性,之後直接調用獲取屬性值的函數,即可獲取配置文件中的值。
此方法同樣存在方法1中的問題。
方法3 通過Environment對象獲取
通過注入獲取Environment對象,然後再根據字段名獲取定義在配置文件的屬性值。示例如下:
@Autowired
private Environment environment;
@Bean
public LettuceConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisConf = new RedisStandaloneConfiguration();
redisConf.setHostName(environment.getProperty("spring.redis.host"));
redisConf.setPort(Integer.parseInt(environment.getProperty("spring.redis.port")));
redisConf.setPassword(RedisPassword.of(environment.getProperty("spring.redis.password")));
return new LettuceConnectionFactory(redisConf);
}
此方法的好處是可以在獲取配置值的代碼段加上try{}catch{}語句,避免程序拋出異常。