问题
Say I need to rely on several implementations of a Spring bean. I have one AccountService interface and two implementations: DefaultAccountServiceImpl and SpecializedAccountServiceImpl.
How is this possible (injecting one or the other implementation) in Spring?
Which implementation will the following injection use?
@Autowired private AccountService accountService;
回答1:
Ad. 1: you can use @Qualifier annotation or autowire using @Resource as opposed to @Autowired which defaults to field name rather than type.
Ad. 2: It will fail at runtime saying that two beans are implementing this interface. If one of your beans is additionally annotated with @Primary, it will be preferred when autowiring by type.
回答2:
@Autowired
@Qualifier("impl1")
BaseInterface impl1;
@Autowired
@Qualifier("impl2")
BaseInterface impl2;
@Component(value="impl1")
public class Implementation1 implements BaseInterface {
}
@Component(value = "impl2")
public class Implementation2 implements BaseInterface {
}
For full code: https://github.com/rsingla/springautowire/
来源:https://stackoverflow.com/questions/11777079/handling-several-implementations-of-one-spring-bean-interface