@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<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>
也许我错过了一些东西。
预先感谢您的回复!
根本原因来自于Java中的泛型定义,因此WalletService<TradeWallet>
is not的一个子类WalletService<Wallet>,
因此Spring无法匹配bean。
其中一个解决方案可以使用上限通配符:
private List<WalletService<? extends Wallet>> walletServices;
还有一种替代方案,它容易出错并且有副作用。如果你注释你的WalletService
这样Spring就为它创建了一个代理对象,既WalletService<TradeWallet>
and WalletService<PersonalWallet>
将被包装到代理对象中,对于外部世界来说,两者看起来都像WalletService
没有任何仿制药信息。一旦你想注射,这就会引起问题,例如,WalletService<TradeWallet>
Spring 将失败,因为两个代理对象都匹配此 bean 定义。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)