1.读取yml的配置@Data @ConfigurationProperties(prefix = "aliyun.sms") public class SmsProperties {private String signName;private String templateCode;private String accessKey;private String secret; }
2.封装方法并注入容器
@Bean
public class SmsTemplate {private SmsProperties properties;public SmsTemplate(SmsProperties properties){this.properties=properties;}public void sendSms(String mobile,String code){try {Config config = new Config().setAccessKeyId(properties.getAccessKey()).setAccessKeySecret(properties.getSecret());config.endpoint = "dysmsapi.aliyuncs.com";com.aliyun.dysmsapi20170525.Client client=new com.aliyun.dysmsapi20170525.Client(config);SendSmsRequest sendSmsRequest = new SendSmsRequest().setPhoneNumbers(mobile).setSignName(properties.getSignName()).setTemplateCode(properties.getTemplateCode()).setTemplateParam("{\"code\":\""+code+"\"}");SendSmsResponse response = client.sendSms(sendSmsRequest);SendSmsResponseBody body = response.getBody();System.out.println(body.getMessage());} catch (Exception e) {e.printStackTrace();}}}