【问题标题】:How to fix RestTemplate NullPointerException in spring boot?如何在 Spring Boot 中修复 RestTemplate NullPointerException?
【发布时间】:2019-10-22 18:56:13
【问题描述】:
@Service
public class RequestSender {

    private static final Logger logger = LoggerFactory.getLogger(RequestSender.class);

    @Autowired
    private RestTemplate restTemplate;

    public MbsFtResponseData sendJsonDataToMBS(final MBSTransactionData transactionData) {
        String mbsUrl = MBSConfigConstants.mbsUrl;
        try {
            logger.info("Sending request method Is Initiated");
            HttpEntity<MBSTransactionData> httpEntity = new HttpEntity<>(transactionData);
            ResponseEntity<MbsFtResponseData> response = restTemplate.exchange(mbsUrl, HttpMethod.POST, httpEntity,
                    MbsFtResponseData.class);
            if (response != null) {
                HttpStatus status = response.getStatusCode();
                if (status.is2xxSuccessful()) {
                    logger.info("Response getting back is succeded with the status code {}", status.value());
                    return response.getBody();
                } else {
                    logger.error("ERROR Response getting back is  with the status code {}", status.value());
                    throw new BBPSMBSException("Error is while connecting to mBS server", status.value());
                }
            } else {
                logger.error("Null value::::::::::::response is null");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("ERROR :::{}:: is occered ", e.getCause());
        }
        return new MbsFtResponseData("Server Not responding or Busy", 500, "FAILED");
    }
}
java.lang.NullPointerException  at com.npst.bbps.middleware.mbs.RequestSender.sendJsonDataToMBS(RequestSender.java:26)  at com.npst.bbps.middleware.mbs.MbsftServiceImpl.mbsFundTransfer(MbsftServiceImpl.java:27)  at com.npst.bbps.middleware.controller.ThirdPartyIntegrationCtrl.initiateRefund(ThirdPartyIntegrationCtrl.java:64)  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

【问题讨论】:

  • 代码中的第 26 行是什么?在该行,您的应用程序收到一个它无法处理的 NULL 值。
  • 请务必在查询中提供完整信息。无法弄清楚原始帖子中的空值。
  • 检查第 26 行的空引用
  • 您能否展示一下restTemplate 的 bean 配置?
  • 它的工作现在@Autowiring 在我身边不起作用

标签: java rest spring-boot


【解决方案1】:

BeanFactory 中找不到RestTemplate bean,因为您不会配置。

您必须在配置文件中定义如下所示的 bean。

@Configuration
public class Config {

   @Bean
   public RestTemplate restTemplate() {
      return new RestTemplate();
   }

}

【讨论】:

  • 我已经完成了,但 @Autowiring 那个时候不工作现在它工作正常
猜你喜欢
  • 2020-05-01
  • 2019-04-28
  • 2019-06-06
  • 2021-06-19
  • 2016-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
相关资源
最近更新 更多