springboot使用properties定義短信模板

通常我們做開發(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

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容