*.jar的成员,继承@Component。
spring-context包里下面的这些注解,你一定知道。
+- context
| +- annotation
| | +- Bean
| | +- ComponentScan
| | +- Configuration
| | +- Import
| | +- Lazy
| | +- Primary
| | +- Profile
| | +- Scope
+- stereotype
| +- Service
| +- Component
| +- Controller
| +- Repository
而 @Value @Autowired 在 spring-beans-**.jar包里(package:org.springframework.beans.factory.annotation); @Mapping @PutMapping @ResponseBody @RestController etc., 在spring-web-**.jar包里(package:org.springframework.web.bind.annotation)。
BTW,@Service 与 @Component 的区别
再说改进项:@ConfigurationProperties取代@Value
org.springframework.boot.context.properties.ConfigurationProperties在spring-boot-**.jar里。用法很easy,指定prefix即可。
需要指明的是,setter方法还是要有的。这里使用lombok的@Setter注解。
其中,oemUserName与property配置项的名称不一致,需要单独用@Value指定,并且value必须用全名 : @Value("${smtp.config.oemName:null}")。
改造后的SmsUtil
package com.emax.zhenghe.common.util;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Slf4j
//↓↓ 声明bean
@Configuration(value = "smsUtil")
@ConditionalOnProperty(prefix = "smtp.config", name = "requestAddress")
//↓↓ properties配置
@ConfigurationProperties(prefix = "smtp.config")
@Setter//必须有setter才能为field赋上值
public class SmsUtil {
private String userName;
private String requestAddress;
private String password;
@Value("${smtp.config.oemName:null}")
private String oemUserName;
private String oemPassWord;
/**
* 发送短信
*/
public String sendSMS(String phone, String msg) {
...
}
/**
* 发送短信
*/
public String sendSMS(String phone, String msg,String userName,String passWord) {
...
}
/**
* 发送短信
*/
public String sendOemSMS(String phone, String msg, String smsSign) {
...
}
}