Spring 4.2.4. List of Autowiring Advanced Common Interfaces

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

Let's pretend that:

 interface A<T extends W>; interface B extends A<W1>; interface C extends A<W2> ; class W1 extends W; class W2 extends W; 

I know that you can enter a list A or a specific A. Can I insert a list A to avoid being explicitly cast from List<A> to List<A<W>> ? Now when I try, I get org.springframework.beans.factory.NoSuchBeanDefinitionException

I think this function is needed to implement a class hierarchy like this:

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

Maybe I missed something. Thank you in advance for your reply!

+4
source share
1 answer

The main reason arises from the generics definition in Java, therefore WalletService<TradeWallet> not a subclass of WalletService<Wallet>, , therefore Spring cannot match beans. Based on solutions, limited wildcards can be used:

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

There is also an alternative that 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 in proxy objects, and for the outside world they look like WalletService without any information about the generics, This causes problems as soon as you want to introduce, say, WalletService<TradeWallet> and Spring will fail, because both proxy objects match this bean definition.

+2
source

Source: https://habr.com/ru/post/1266628/


All Articles