英文:
Why @Autowired does not work with generic type T?
问题
我有以下的类,在其中我尝试注入一个JpaRepository
的依赖。
class Sample<T> implements SampleInterface<T> {
@Autowired
JpaRepository<T, Long> jpaRepository; // 希望Spring能够使用实体A来注入这个依赖
}
class Main {
@Bean
Sample<A> sample() {
return new Sample<A>(); // A是一个JPA实体
}
}
是因为注解在编译期间解析的吗?为什么Spring不能够使用泛型来动态进行自动装配?我可能忽略了一些基础知识,但很想填补这个知识空白。
英文:
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.
答案1
得分: 2
这是由于类型擦除,在编译时发生,而Bean注入则发生在运行时。
由于对其没有限制,T
被擦除,基本上被 Object
替代,因此 Spring Data 无法为 Object
创建存储库。
另请参阅 https://stackoverflow.com/questions/19417670/using-generics-in-spring-data-jpa-repositories
英文:
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 https://stackoverflow.com/questions/19417670/using-generics-in-spring-data-jpa-repositories
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论