在使用@Component
注解的工具类中,注入RestTemplate
和读取nacos配置@Value
注解读取失败。解决办法是使用@PostConstruct
注解进行初始化。
@Component
public class SmsUtil {
private static SmsUtil smsUtil;
private static RestTemplate restTemplate;
private static String baseUrl;
private static String sendOrBalanceUrl;
private static String statusUrl;
private static String modifyPwdUrl;
private static String userid;
private static String account;
private static String password;
private static String isEnable;
@PostConstruct
public void init() {
smsUtil = this;
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
@Autowired
public void setRestTemplate(RestTemplate restTemplate) {
SmsUtil.restTemplate = restTemplate;
}
@Value("${sms.baseUrl}")
public void setBaseUrl(String baseUrl) {
SmsUtil.baseUrl = baseUrl;
}
@Value("${sms.sendOrBalanceUrl}")
public void setSendOrBalanceUrl(String sendOrBalanceUrl) {
SmsUtil.sendOrBalanceUrl = sendOrBalanceUrl;
}
@Value("${sms.statusUrl}")
public void setStatusUrl(String statusUrl) {
SmsUtil.statusUrl = statusUrl;
}
@Value("${sms.modifyPwdUrl}")
public void setModifyPwdUrl(String modifyPwdUrl) {
SmsUtil.modifyPwdUrl = modifyPwdUrl;
}
@Value("${sms.userid}")
public void setUserid(String userid) {
SmsUtil.userid = userid;
}
@Value("${sms.account}")
public void setAccount(String account) {
SmsUtil.account = account;
}
@Value("${sms.password}")
public void setPassword(String password) {
SmsUtil.password = password;
}
@Value("${sms.isEnable}")
public void setIsEnable(String isEnable) {
SmsUtil.isEnable = isEnable;
}
private JSONObject restTemplateHttpSend(String url, String param) {
JSONObject resObject = null;
try {
ResponseEntity<String> responseEntity = restTemplate.exchange(baseUrl + url + param, HttpMethod.POST, null, String.class);
HttpStatus statusCode = responseEntity.getStatusCode();
if (statusCode == HttpStatus.OK) {
log.info(">>>http返回结果:", responseEntity.getBody());
resObject = JSON.parseObject(responseEntity.getBody());
}
} catch (Exception e) {
e.printStackTrace();
}
return resObject;
}
}
References:
最新评论
不错挺好用的,东至梅城何红涛林场的 何红涛2个月前 (10-18)回复
识别码不对
呵呵
我的是ipv4网络,如何使用直播源啊!