问题
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