Handling several implementations of one Spring bean/interface

白昼怎懂夜的黑 提交于 2019-12-29 04:36:09

问题


Say I need to rely on several implementations of a Spring bean. I have one AccountService interface and two implementations: DefaultAccountServiceImpl and SpecializedAccountServiceImpl.

  1. How is this possible (injecting one or the other implementation) in Spring?

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!