@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;
我知道可以注入(inject) A 列表或特定 A。我可以注入(inject) 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>
不是 WalletService<Wallet>,
的子类因此 Spring 无法匹配 bean。
解决方案之一可能是使用上界通配符:
private List<WalletService<? extends Wallet>> walletServices;
还有一个替代方案,它容易出错并且有副作用。如果你注释你的 WalletService
以便 Spring 为它创建一个代理对象,两者都是 WalletService<TradeWallet>
和 WalletService<PersonalWallet>
将被包装到代理对象中,对于外部世界,两者看起来都像 WalletService
没有任何泛型信息。一旦您想注入(inject),这就会导致问题,例如 WalletService<TradeWallet>
并且 Spring 将失败,因为两个代理对象都匹配这个 bean 定义。
关于java - Spring 4.2.4。扩展通用接口(interface)的 Autowiring 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35749819/