最近在做快捷登錄的功能,就是通過手機號和短信驗證碼進行登錄。有個需求是測試環境不發送驗證碼和短信驗證。我通過配置 Properties文件定義開關來控制是否進行短信發送和驗證。我是通過 Spring @PropertySource來實現的。
使用@PropertySource操作步驟
通過@PropertySource引入Properties配置文件操作步驟如下:
- 創建配置類並在配置類上聲明@PropertySource標籤例如:
@PropertySource(value={"classpath:sms.properties"})
- 同時在該標籤上聲明@Component標籤
- 通過 @Value標籤將Properties配置屬性配置到配置類的成員變量中。
@Value(value="${sms.sign}")
private String smsSign;
- 在需要使用配置類的Spring Bean中 通過@Autowired 注入到需要的地方。
具體的代碼示例
sms.properties 的代碼如下:
## 0 close 1 open
sms.sign=0
配置類的代碼如下:
package com.alicom.dysms;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource(value={"classpath:sms.properties"})
public class SMSConfig {
@Value(value="${sms.sign}")
private String smsSign;
public String getSmsSign() {
return smsSign;
}
public void setSmsSign(String smsSign) {
this.smsSign = smsSign;
}
}
在我們登錄Controller中引入短信配置類具體代碼如下:
@Controller
@RequestMapping("/passport")
public class PassportController extends SpringControllerSupport {
@Autowired
private SMSConfig sMSProperty;
//下面代碼就省略了........
}