假设我想创建一个 REST API,它对多个实体执行基本的 CRUD 操作。为此,我创建了通用接口:
public interface CrudService<T>{
//generic CRUD methods
}
Run Code Online (Sandbox Code Playgroud)
及其对Foo实体的实现:
@Entity
public class Foo {
}
@Repository
public interface FooRepository extends JpaRepository<Foo, Long>{
}
@Service
@Transactional
public class FooCrudServiceImpl implements CrudService{
@Autowired
private FooRepository repository;
//CRUD methods implementation
}
@RestController
class FooController{
@Autowired
private CrudService<Foo> crudService;
//Controller methods
}
Run Code Online (Sandbox Code Playgroud)
我现在想要避免的是为每个实体创建具有基本相同逻辑的服务实现。所以我尝试创建一个可以从多个控制器(FooController、BarController 等)调用的通用服务类:
@Service
@Transactional
class GenericCrudServiceImpl<T> implements CrudService{
@Autowired
private JpaRepository<T, Long> repository;
//generic CRUD methods implementation
}
Run Code Online (Sandbox Code Playgroud)
并将该服务类传递给将指定实体类型的每个控制器。问题是将有多个存储库 bean 可以注入GenericCrudServiceImpl(FooRepository、BarRepository 等),并且仅通过指定JpaRepositorySpring的类型仍然不知道要注入哪个 …