通常我們做開發(fā)時(shí)候會(huì)遇到短信發(fā)送郵件發(fā)送之類的需求,發(fā)送內(nèi)容往往會(huì)由客戶提供一個(gè)模板,如果我們是在程序里拼接字符串來搞定這個(gè)模板,很明顯是一種坑隊(duì)友的做法。一般將模板放入properties文件中,使用的時(shí)候替換其中的一些變量即可。
本文我們使用springboot來實(shí)現(xiàn)根據(jù)模板發(fā)送短信驗(yàn)證碼的功能。
tips:
1、正則表達(dá)式
2、springboot讀取properties文件
模板定義
將需要定義的短信模板都定義在msg.properties文件,目錄同application.properties,注意其中的【{code}】即為要替換的變量。
tem.msg.verify.code=驗(yàn)證碼為:{code},請(qǐng)勿泄露給其他人。
讀取properties
定義組件MSGConstants,指定需要加載的properties文件,用來讀取定義的模板,使用spring的@Value注解
@PropertySource("classpath:msg.properties")
@Component
public class MSGConstatns {
@Value("${tem.msg.verify.code}")
private String sendCodeMsg;
public String getSendCodeMsg() {
return sendCodeMsg;
}
public void setSendCodeMsg(String sendCodeMsg) {
this.sendCodeMsg = sendCodeMsg;
}
}
解析模板工具類
考慮到公用,將參數(shù)設(shè)置為Map,即需要替換的變量,正則表達(dá)式替換找到對(duì)應(yīng)的key,
我這里key的格式為:{key},可根據(jù)自己情況進(jìn)行修改,同時(shí)修改正則。
public static String getContent(Map<String, String> params,String content) {
String reg = "\\{\\w*}";//
Pattern pattern = Pattern.compile(reg);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String group = matcher.group();//
String key = group.substring(1, group.length() - 1);
if (!params.containsKey(key))
throw new NormalException("未找到需要替換的key:" + key);
content = content.replace(group, params.get(key));
}
return content;
}
測(cè)試
一個(gè)很簡(jiǎn)單的ajax請(qǐng)求,返回獲取到的短信內(nèi)容
@RestController
@RequestMapping("demo")
public class DemoController {
@Resource
private MSGConstatns msgConstatns;
@RequestMapping("msg")
public String msgContent(){
String code = "123456";//正式開發(fā)中一般采用隨機(jī)數(shù)
Map<String,String> params = new HashMap<>();
params.put("code",code);
return SendCodeUtil.getContent(params,msgConstatns.getSendCodeMsg());
}
}
結(jié)果
期望值:驗(yàn)證碼為:123456,請(qǐng)勿泄露給其他人
實(shí)際效果:

結(jié)果.png