春季4.2.4。 自动assembly扩展通用接口列表

@Autowired private List<WalletService> walletServices; //Doesn't work @Autowired private List walletServices; //Everything is fine 

假设我们有:

 interface A; interface B extends A; interface C extends A ; class W1 extends W; class W2 extends W; 

我知道可以注入A或特定A的列表。我可以注入A列表以避免从List to List<A>的显式List to List<A>吗? 现在,当我尝试一些时,我得到了org.springframework.beans.factory.NoSuchBeanDefinitionException

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

 interface WalletService interface TradeWalletService extends WalletService interface PersonalWalletService extends WalletService 

也许我错过了一些东西。 在此先感谢您的回复!

根本原因来自Java中的generics定义,因此WalletService 不是 WalletService,的子类WalletService,因此Spring无法匹配bean。 解决方案可以使用上限有界通配符:

 private List> walletServices; 

还有一种替代方案,它容易出错并且有副作用。 如果您为WalletService注释以便Spring WalletService创建代理对象,则WalletServiceWalletService将被包装到代理对象中,对于外部世界,它们看起来都像WalletService没有任何generics信息。 一旦你想注入WalletService就会导致问题,并且Spring会失败,因为两个代理对象都匹配这个bean定义。