为什么 @Autowired 在泛型类型 T 中不起作用?

huangapple go评论108阅读模式
英文:

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&lt;T&gt; implements SampleInterface&lt;T&gt; {
  @Autowired
  JpaRepository&lt;T, Long&gt; jpaRepository; // Want this to be injected by spring using A as entity
}
 
 
 class Main {
    @Bean
    Sample&lt;A&gt; sample() {
      return new Sample&lt;A&gt;(); // 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

huangapple
  • 本文由 发表于 2020年4月4日 02:56:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/61018712.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定