Spring data: Autowire JpaRepository (Generic type)

我是研究僧i 提交于 2019-12-25 02:46:14

问题


I have a service (for generic type) which uses findAll() function of JpaRepository.

public class SomeService<EntityClass>{
    @Autowired
    JpaRepository<EntityClass> repository;

   JpaRepository getRepository(){}
}

But it gives this error:

No qualifying bean of type [org.springframework.data.jpa.repository.JpaRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations

Is there any way to construct JpaRepository dynamically? The service classes won't have specific implementations for each Entity. i.e. I need to use Service class like this:

@Autowired
SomeService<Fruit> fruitService;

This means that, Service class won't know about entity class in compile time.

Now if I create Repositories extending JpaRepository, then it still won't work: Say I create:

FruitRepository extends JpaRepository<Fruit, Long>
PersonRepository extends JpaRepository<Person, Long>

then spring gives this error:

org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.jpa.repository.JpaRepository] is defined: expected single matching bean but found 2

I am having to do this:

public class PersonService<Person>{
    @Autowired
    PersonRepository repository;
   JpaRepository getRepository() {return repository;}
}

Of course my entities are not really Fruit and Person, but the main point is all of them will have common "services" with identical implementations.

How do I implement so that it will be possible to define only single service class and autowire it by specifying entity class?

来源:https://stackoverflow.com/questions/31154382/spring-data-autowire-jparepository-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!