springboot阿里云短信服务自定义自动装配

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值