【问题标题】:Spring 4.2.4. Autowiring list of extended generic interfaces春天 4.2.4。扩展通用接口的自动装配列表
【发布时间】:2016-03-02 14:22:15
【问题描述】:
@Autowired
private List<WalletService<Wallet>> walletServices; //Doesn't work

@Autowired
private List<WalletService> walletServices; //Everything is fine

假设我们有:

interface A<T extends W>;
interface B extends A<W1>;
interface C extends A<W2> ;
class W1 extends W;
class W2 extends W;

我知道可以注入 A 列表或特定 A。我可以注入 A 列表以避免来自 List&lt;A&gt; to List&lt;A&lt;W&gt;&gt; 的显式转换吗? 现在,当我尝试一些时,我得到 org.springframework.beans.factory.NoSuchBeanDefinitionException

我认为这个特性对于实现这样的类层次结构是必要的:

interface WalletService<T exends Wallet>
interface TradeWalletService extends WalletService<TradeWallet>
interface PersonalWalletService extends WalletService<PersonalWallet>

也许我错过了什么。 提前感谢您的回复!

【问题讨论】:

  • 你的春季版本是什么?
  • Spring 4.2.4 版本。
  • @DmRomantsov 你能解决这个问题吗?我面临着类似的问题,无法使用任何语法自动装配

标签: java spring


【解决方案1】:

根本原因来自 Java 中的泛型定义,因此 WalletService&lt;TradeWallet&gt; 不是 WalletService&lt;Wallet&gt;, 的子类,因此 Spring 无法匹配 bean。 其中一个解决方案可能是使用上限通配符:

private List<WalletService<? extends Wallet>> walletServices;

还有一种替代方法,它容易出错并且有副作用。如果您注释 WalletService 以便 Spring 为其创建代理对象,则 WalletService&lt;TradeWallet&gt;WalletService&lt;PersonalWallet&gt; 都将被包装到代理对象中,并且对于外部世界,它们看起来都像 WalletService 没有任何泛型信息。这会在您想要注入时立即导致问题,例如,WalletService&lt;TradeWallet&gt;,并且 Spring 将失败,因为两个代理对象都匹配此 bean 定义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多