通常我们的项目至少会有一个用来存放各种参数的参数类,而这些参数又希望在application配置文件里面能进行设置,那么如何将配置文件里面的配置参数自动装配到参数类中?
如,application.yml里面有参数如下:
mq:
sms:
sms-queue: smsQueue
sms-exchange: smsExchange
sms-key: smsKey
参数类应该要实现InitializingBean 接口,才能在属性设置完毕后再进行默认值赋值:
@Configuration("smsConstants")
@ConfigurationProperties("mq.sms")
public class SMSConstants implements InitializingBean {
private String smsQueue;
private String smsExchange;
private String smsKey;
@Override
public void afterPropertiesSet() throws Exception {
if (!StringUtils.hasText(smsQueue)){
smsQueue="smsQueue";
}
if (!StringUtils.hasText(smsExchange)){
smsExchange="smsExchange";
}
if (!StringUtils.hasText(smsKey)){
smsKey="sms.direct";
}
}
public String getSmsQueue() {
return smsQueue;
}
public void setSmsQueue(String smsQueue) {
this.smsQueue = smsQueue;
}
public String getSmsExchange() {
return smsExchange;
}
public void setSmsExchange(String smsExchange) {
this.smsExchange = smsExchange;
}
public String getSmsKey() {
return smsKey;
}
public void setSmsKey(String smsKey) {
this.smsKey = smsKey;
}