本文介绍了春季4.2.4。自动装配扩展通用接口列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@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>的显式转换列出< A< W>>
现在,当我尝试一些时,我得到了org.springframework.beans.factory.NoSuchBeanDefinitionException

I know it is possible to inject a list of A or specific A. Can I inject a list of A to avoid an explicit cast from List<A> to List<A<W>>?Now, when I try some i get org.springframework.beans.factory.NoSuchBeanDefinitionException

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

I think this feature is necessary to implementation a hierarchy of classes like this:

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

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

Maybe I'm missing something. Thanks in advance for your reply!

推荐答案

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

The root cause comes from the generics definition in Java, so that WalletService<TradeWallet> is not a subclass of WalletService<Wallet>, therefore Spring cannot match the beans.On of the solutions could be using upper bounded wildcards:

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

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

There is also an alternative, which is error-prone and has side effects. If you annotate your WalletService so that Spring creates a proxy object for it, both WalletService<TradeWallet> and WalletService<PersonalWallet> will be wrapped into proxy objects and for the outer world both look like WalletService w/o any generics information. This causes problems as soon as you want to inject, say, WalletService<TradeWallet> and Spring will fail as both proxied object match this bean definition.

这篇关于春季4.2.4。自动装配扩展通用接口列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 04:04