java 处理一个 Spring bean/接口的多个实现

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11777079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 06:19:40  来源:igfitidea点击:

Handling several implementations of one Spring bean/interface

javaspringinterface

提问by balteo

Say I need to rely on several implementationsof a Spring bean. I have one AccountServiceinterface and two implementations: DefaultAccountServiceImpland SpecializedAccountServiceImpl.

假设我需要依赖Spring bean 的几种实现。我有一个AccountService接口和两个实现:DefaultAccountServiceImplSpecializedAccountServiceImpl.

  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. 这在 Spring 中怎么可能(注入一个或另一个实现)?

  2. 以下注入将使用哪种实现?

    @Autowired
    private AccountService accountService;
    

回答by Tomasz Nurkiewicz

Ad. 1: you can use @Qualifierannotationor autowire using @Resourceas opposed to @Autowiredwhich defaults to field name rather than type.

广告。1:可以使用@Qualifier注释使用或自动装配@Resource,而不是@Autowired默认为字段名称,而不是类型。

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:它会在运行时失败,说两个 bean 正在实现这个接口。如果您的一个 bean 还附加了注释@Primary,则在按类型自动装配时将首选它。

回答by Rajeev Singla

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