我使用一个小型 Spring 应用程序,其中数据库中的值很少,我想使用可变调用来检索它们。
API 在这里,
@RestController
@RequestMapping("/api/v1/products")
public class ProductAPI {
private ProductService service;
@Autowired
public void setService(ProductService service) {
this.service = service;
}
@GetMapping("/stock/")
public ResponseEntity<Product> findById(@RequestParam("productId") String productId) {
Product product = service.findById(productId).get();
return ResponseEntity.of(Optional.of(product));
}
...........
}
服务调用,
@Service
public class ProductService {
private ProductRepository repository;
@Autowired
public void setProductRepository(ProductRepository productRepository) {
this.repository = productRepository;
}
public Optional<Product> findById(String id) {
return repository.findById(id);
}
}
存储库类,
@Repository
public interface ProductRepository extends CrudRepository<Product, String>{
}
当我使用 cURL 调用电话时,我收到消息,
$ curl -X GET http://localhost:8080/api/v1/products/stock?productId=Product%20ID | jq
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 142 0 142 0 0 845 0 --:--:-- --:--:-- --:--:-- 850
{
"timestamp": "2019-02-25T12:19:31.797+0000",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/api/v1/products/stock"
}
我已正确插入数据库中的条目。这里有什么问题吗?
最佳答案
因为您的映射中有额外的/
@GetMapping("/stock/")
所以如果你想要这样的请求
curl -X GET http://localhost:8080/api/v1/products/stock/?productId=Product%20ID
您需要如下映射:
@GetMapping("/stock")
在您当前的版本中,右旋度看起来像:
http://localhost:8080/api/v1/products/stock/?productId=Product%20ID
关于Java "error": "Not Found", "message": "No message available",,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54865998/