springboot使⽤properties定义短信模板的⽅法教程
前⾔
通常我们做开发时候会遇到短信发送邮件发送之类的需求,发送内容往往会由客户提供⼀个模板,如果我们是在程序⾥拼接字符串来搞定这个模板,很明显是⼀种坑队友的做法。⼀般将模板放⼊properties⽂件中,使⽤的时候替换其中的⼀些变量即可。
本⽂我们使⽤springboot来实现根据模板验证码的功能,下⾯话不多说了,来⼀起看看详细的介绍吧。
tips:
1、正则表达式
2、springboot读取properties⽂件
模板定义
将需要定义的短信模板都定义在msg.properties⽂件,⽬录同application.properties,注意其中的【[code]】即为要替换的变量。
tem.de=验证码为:[code],请勿泄露给其他⼈。
读取properties
定义组件MSGConstants,指定需要加载的properties⽂件,⽤来读取定义的模板,使⽤spring的@Value注解
@PropertySource("classpath:msg.properties")
@Component
public class MSGConstatns {
@Value("${tem.de}")
private String sendCodeMsg;
public String getSendCodeMsg() {
return sendCodeMsg;
}
public void setSendCodeMsg(String sendCodeMsg) {
this.sendCodeMsg = sendCodeMsg;
}
}
解析模板⼯具类
考虑到公⽤,将参数设置为Map,即需要替换的变量,正则表达式替换到对应的key,我这⾥key的格式为:{key},可根据⾃⼰情况进⾏修改,同时修改正则。
spring怎么读取propertiespublic static String getContent(Map<String, String> params,String content) {
String reg = "\\{\\w*}";//
Pattern pattern = Patternpile(reg);
Matcher matcher = pattern.matcher(content);
while (matcher.find()) {
String group = up();//
String key = group.substring(1, group.length() - 1);
if (!ainsKey(key))
throw new NormalException("未到需要替换的key:" + key);
content = place(group, (key));
}
return content;
}
测试
⼀个很简单的ajax请求,返回获取到的短信内容
@RestController
@RequestMapping("demo")
public class DemoController {
@Resource
private MSGConstatns msgConstatns;
@RequestMapping("msg")
public String msgContent(){
String code = "123456";//正式开发中⼀般采⽤随机数
Map<String,String> params = new HashMap<>();
params.put("code",code);
Content(SendCodeMsg());
}
}
结果
期望值:验证码为:123456,请勿泄露给其他⼈
实际效果:
总结
以上就是这篇⽂章的全部内容了,希望本⽂的内容对⼤家的学习或者⼯作具有⼀定的参考学习价值,如果有疑问⼤家可以留⾔交流,谢谢⼤家对的⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。