我正在尝试创建一个抽象类来执行所需的常见REST操作,但如果我正在尝试做的事情是可能的话,则无法解决。我已经尝试了很多方法,但是已经将下面的代码剥夺了它应该如何在我脑海中起作用
根据以下建议更新课程。现在的问题是具体类中的构造函数是无效的,因为CustomerRepository不能分配给JpaRepository,尽管它扩展了该接口。
AbstractRestController
public abstract class AbstractRestController<T> {
private final JpaRepository<T, Serializable> repository;
public AbstractRestController(JpaRepository<T, Serializable> repository) {
this.repository = repository;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResponseBody<T>> getOne(@PathVariable Long id) {
T restObj = repository.findOne(id);
JsonResponseBody<T> response = new JsonResponseBody<>(ResponseStatus.SUCCESS, restObj);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(response);
}
protected JpaRepository<T, Serializable> getRepository() {
return repository;
}
}
CustomerController
@RestController
@RequestMapping(value = "/api/v1/customer")
public class CustomerController extends AbstractRestController<Customer> {
@Autowired
public CustomerController(CustomerRepository repository){
super(repository);
}
}
CustomerRepository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
答案 0 :(得分:5)
实际上,正如@ dino-tw所提到的,您正在尝试实例化具有未定义依赖关系的抽象类。您绝对可以拥有一个抽象控制器类,甚至可以定义将由所有子类继承的请求处理方法。试试这个:
public abstract class AbstractRestController<T, ID extends Serializable> {
private final JpaRepository<T, ID> repository;
public AbstractRestController(JpaRepository<T, ID> repository){
this.repository = repository;
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<JsonResponseBody<T>> getOne(@PathVariable ID id) {
T restObj = repository.findOne(id);
JsonResponseBody<T> response = new JsonResponseBody<>(ResponseStatus.SUCCESS, restObj);
return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON_UTF8).body(response);
}
protected JpaRepository<T, ID> getRepository(){ return repository; }
}
@RestController
@RequestMapping(value = "/api/v1/customer")
public class CustomerController extends AbstractRestController<Customer, Long> {
@Autowired
public CustomerController(CustomerRepository repository){
super(repository);
}
}