java - Spring 4.2.4。扩展通用接口(interface)的 Autowiring 列表

标签 java spring

@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/

相关文章:

java - OpenShift 在线 - 构建时内存不足

java - Spring Autowire 在同一类中创建 Bean 结果为 :Requested bean is currently in creation Error*

java - eclipse spring boot 启动项目给出错误

java - Spring 3.2 Security - 使用非唯一用户名和附加信息登录

java - 如何在 Spring Boot 中实现 UDP 服务器以读取来自客户端的输入

Java Spring - 在 Wildfly 11 中禁用发送到 server.log 的任何日志记录

java - Elasticsearch:获取路径下的嵌套对象不是嵌套类型

java - 如何在 Java 中创建两个元素之间的关系?

java - 回答 从 1 个 Android 应用程序访问另一个应用程序的相同数据

java - 这种Java/Swing接口(interface)的名称是什么?