【发布时间】:2022-01-11 00:09:47
【问题描述】:
我想做一个简单的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;
}
}
一个简单的存储库和一个使用 DB 的服务:
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
我尝试谷歌,但没有找到错误和问题的解决方案。你能告诉我我做错了什么吗?
application.propertires:
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
【问题讨论】:
标签: spring spring-restcontroller