我想做一個spring與MongoDB互動的簡單例子。我有一個產品型號:
@NoArgsConstructor
@ToString(exclude = {"id"})
public class Product {
@Id
private String id;
private String name;
private Integer price;
private LocalDateTime localDateTime;
public Product(String name, Integer price, LocalDateTime localDateTime) {
this.name = name;
this.price = price;
this.localDateTime = localDateTime;
}
}
一個簡單的存盤庫和一個用于處理資料庫的服務:
public interface productRepository extends MongoRepository<Product,String> {
Product findByName(String name);
List<Product> findByPrice(Integer price);
}
服務:
@AllArgsConstructor
@Service
public class productServiceImpl implements productService<Product>{
productRepository repository;
@Override
public Product saveOrUpdateProduct(Product product) {
return repository.save(product);
}
@Override
public List<Product> findAll() {
return repository.findAll();
}
@Override
public Product findByName(String name) {
return repository.findByName(name);
}
@Override
public List<Product> findByPrice(Integer price) {
return repository.findByPrice(price);
}
}
當我檢查 的作業時findAll,一切正常。但是在使用 Rest Service 時:
@RestController("/products")
@AllArgsConstructor
public class productRestController {
productServiceImpl productService;
@GetMapping("/")
public List<Product> getAllProducts(){
System.out.println("*********************inside get all ***********************");
return productService.findAll();
}
@GetMapping("/products/{name}")
public Product getProductsByName(@PathVariable("name")Optional<String> name ){
if(name.isPresent())
return productService.findByName(name.get());
else return null;
}
@GetMapping("/products/{price}")
public List<Product> getProductsByPrice(@PathVariable("price")Optional<Integer> price ){
if(price.isPresent())
return productService.findByPrice(price.get());
else return null;
}
@PostMapping("/save")
public ResponseEntity<?> saveProduct(@RequestBody Product product){
Product p = productService.saveOrUpdateProduct(product);
return new ResponseEntity(p, HttpStatus.OK);
}
}
并呼叫http://localhost:8080/products/我得到一個錯誤:
No adapter for handler [com.example.MongoTesr.REST.productRestController@6e98d209]:
The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler
我嘗試谷歌但沒有找到錯誤和問題的解決方案。你能告訴我我做錯了什么嗎?
應用程式屬性:
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=root
spring.data.mongodb.password=rootpassword
spring.data.mongodb.database=test_db
spring.data.mongodb.port=27017
spring.data.mongodb.host=localhost
uj5u.com熱心網友回復:
@RestController("/products") 不做你想的!
/products 不是路徑或映射到它或類似的,而只是:
該值可能指示對邏輯組件名稱的建議,在自動檢測到的組件的情況下將其轉換為 Spring bean。
來自RestController.valuejavadoc。
如果我們想在類級別構建我們的路徑映射,我們可以通過以下方式實作:
...
@RestController // resp. @Controller
@RequestMapping("/products") //(resp. relative: "products")
public class ...
另請參閱:在類級別使用@RequestMapping
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/372970.html
