优米格
分享有营养的

@Component使用@Autowired注入失败报空指针异常

在使用@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:

  1. Why use @PostConstruct?
  2. @PostConstruct
赞(1)
未经允许禁止转载:优米格 » @Component使用@Autowired注入失败报空指针异常

评论 抢沙发

合作&反馈&投稿

商务合作、问题反馈、投稿,欢迎联系

广告合作侵权联系