gpt4 book ai didi

从另一个类调用该方法时,DiscoveryClient 上出现 java.lang.NullPointerException

转载 作者:行者123 更新时间:2023-12-02 02:15:08 24 4
gpt4 key购买 nike

当我通过浏览器调用该方法本身时,它正在工作,并且我得到了预期的 JSON。因此该方法正在运行并且所请求的服务已注册。

    @RequestMapping("/getArticle/{articleId}")
public String getArticle(@PathVariable("articleId") Integer articleId) {
// {"articleId":47,"name":"test","price":5.0}
List<ServiceInstance> instances =
discoveryClient.getInstances("articlemicroservice"); //null when calling
ServiceInstance serviceInstance = instances.get(0);
String baseUrl = serviceInstance.getUri().toString();

baseUrl = baseUrl + "/db/find/" + articleId.toString();

System.out.println("BASEURL: " + baseUrl);

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = null;

try {
response = restTemplate.exchange(baseUrl, HttpMethod.GET,
getHeaders(), String.class);
} catch (Exception ex) {
System.out.println(ex);
}
// {"articleId":47,"name":"test","price":5.0}
String articleEntity = response.getBody().toString();
System.out.println("articleEntity: " + articleEntity);
return articleEntity;
}

当我从另一个类(位于同一项目中)调用该方法时,我收到一个 NullPointerException

    @GetMapping(path = "/addCartItemToCart/{cartId}/{articleId}/{quantity}")
public @ResponseBody String addCartItemToCart(@PathVariable("cartId")
Integer cartId,
@PathVariable("articleId") Integer articleId,
@PathVariable("quantity") Integer quantity) {

ArticleMicroserviceRestConnectorRequester n = new
ArticleMicroserviceRestConnectorRequester();

String article = n.getArticle(articleId); //calling the method here
JSONObject json = new JSONObject(article);
CartItemEntity cartItemEntity = new CartItemEntity();
cartItemEntity.setArticleId(json.getInt("articleId"));
cartItemEntity.setQuantity(quantity);
cartItemEntity.setCartItemId(cartId);
CartEntity cartEntity = cartRepository.findById(cartId).get();
cartEntity.addCartItem(cartItemEntity);
cartEntity.setNumberOfCartItems(cartEntity.getNumberOfCartItems() +
cartItemEntity.getQuantity());
cartRepository.save(cartEntity);
return "Saved";
}

异常:

java.lang.NullPointerException: null
在 de.leuphana.jee.connector.jpa.behaviour.ArticleMicroserviceRestConnectorRequester.getArticle(ArticleMicroserviceRestConnectorRequester.java:44) ~[classes/:na]
...

最佳答案

addCartItemToCart 中,您创建一个 ArticleMicroserviceRestConnectorRequester 的新实例。它不是由 Spring 管理的,因此 discoveryClient 不是 Autowiring 的,它是 null。

您必须将ArticleMicroserviceRestConnectorRequester注入(inject)到您的其他类中。因此,您将获得一个由 Spring 管理的实例,并且应该具有 Autowiring /注入(inject)的 discoveryClient

关于从另一个类调用该方法时,DiscoveryClient 上出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49408401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com