简体   繁体   English

为什么@Autowired 不适用于泛型类型 T?

[英]Why @Autowired does not work with generic type T?

I have below class where I am trying to inject some JpaRepository dependency.我在 class 下面尝试注入一些JpaRepository依赖项。

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?为什么 spring 不能使用 generics 使自动装配动态化? I may be missing the fundamentals, but curious to fill that knowledge gap.我可能缺少基础知识,但很想填补这个知识空白。

The reason for this is type erasure which happens at compile time while bean injection happens at runtime.原因是类型擦除发生在编译时,而 bean 注入发生在运行时。

Since there are no bounds on it T gets erased and basically replaced by Object and Spring Data can't create repositories for Object .由于它没有界限,因此T被删除并基本上被Object和 Spring 数据替换为Object的存储库。

See also Using generics in Spring Data JPA repositories另请参阅在 Spring 数据 JPA 存储库中使用 generics

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM