春季4.2.4.自动装配扩展通用接口列表

DmR*_*sov 6 java spring

@Autowired
private List<WalletService<Wallet>> walletServices; //Doesn't work

@Autowired
private List<WalletService> walletServices; //Everything is fine
Run Code Online (Sandbox Code Playgroud)

假设我们有:

interface A<T extends W>;
interface B extends A<W1>;
interface C extends A<W2> ;
class W1 extends W;
class W2 extends W;
Run Code Online (Sandbox Code Playgroud)

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

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

interface WalletService<T exends Wallet>
interface TradeWalletService extends WalletService<TradeWallet>
interface PersonalWalletService extends WalletService<PersonalWallet>
Run Code Online (Sandbox Code Playgroud)

也许我错过了什么.在此先感谢您的回复!

xwa*_*ndi 6

根本原因来自Java中的泛型定义,因此WalletService<TradeWallet> 不是 Java 的子类,WalletService<Wallet>,因此Spring无法匹配Bean。其中一种解决方案可以使用上限通配符:

private List<WalletService<? extends Wallet>> walletServices;
Run Code Online (Sandbox Code Playgroud)

还有一种替代方法,它容易出错并且具有副作用。如果您的注释WalletService,使春季为其创建一个代理对象,都WalletService<TradeWallet>WalletService<PersonalWallet>将被包装成代理对象和外部世界都看起来像WalletServiceW / O任何仿制药信息。例如,这会引起问题,WalletService<TradeWallet>因为两个代理对象都与此bean定义匹配,因此Spring将失败。