Reputation: 4602
I have below class where I am trying to inject some JpaRepository
dependency.
class Sample<T> implements SampleInterface<T> {
@Autowired
JpaRepository<T, Long> jpaRepository; // Want this to be injected by spring using A as entity
}
class Main {
@Bean
Sample<A> sample() {
return new Sample<A>(); // A is a jpa entity
}
}
Is it because annotations are parsed during compilation? Why can't spring make the autowiring dynamic using generics? I may be missing the fundamentals, but curious to fill that knowledge gap.
Upvotes: 1
Views: 335
Reputation: 81907
The reason for this is type erasure which happens at compile time while bean injection happens at runtime.
Since there are no bounds on it T
gets erased and basically replaced by Object
and Spring Data can't create repositories for Object
.
See also Using generics in Spring Data JPA repositories
Upvotes: 2