1.创建SmsTemplate类对业务代码进行封装
mobile:手机号 code:发送的验证码
public void sendSms(String mobile , String code){
try {
Config config = new Config()
.setAccessKeyId(smsProperties.getAccessKeyId())
.setAccessKeySecret(smsProperties.getAccessKeySecret());
config.endpoint = "dysmsapi.aliyuncs.com";
Client client = new Client(config);
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(mobile)
.setSignName(smsProperties.getSignName())
.setTemplateCode(smsProperties.getTemplateCode())
.setTemplateParam("{\"code\":\""+code+"\"}");
SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
SendSmsResponseBody body = sendSmsResponse.getBody();
System.out.println(body.getMessage());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
2.定义一个Properties类动态获取业务代码中配置参数
setAccessKeyId() setAccessKeySecret() setSignName() setTemplateCode()
@ConfigurationProperties(prefix = "tanhua.sms") 指定前缀,绑定配置文件中的配置
@Data
@ConfigurationProperties(prefix = "tanhua.sms")
public class SmsProperties {
private String accessKeyId;
private String accessKeySecret;
private String domain;
private String signName;
private String templateCode;
}
3.定义一个SmsAutoConfiguration类启动配置类
创建SmsTemplate的javaBean并传入SmsProperties(在SmsProperties创建构造函数为变量Smsproperties赋值)
@EnableConfigurationProperties({
SmsProperties.class
})
public class SmsAutoConfiguration {
@Bean
public SmsTemplate getsmsTemplate(SmsProperties properties){
return new SmsTemplate(properties);
}
}
private SmsProperties smsProperties;
public SmsTemplate(SmsProperties properties){
this.smsProperties = properties;
}
4.在resources根目录下创建META-INF文件夹并创建spring.factories文件
在factories文件中配置EnableAutoConfiguration指向SmsAutoConfiguration类
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.gb.tanHua.autoConfig.SmsAutoConfiguration
5.相关jar包
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.23</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.28</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>