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
Handling several implementations of one Spring bean/interface
提问by balteo
Say I need to rely on several implementationsof a Spring bean. I have one AccountService
interface and two implementations: DefaultAccountServiceImpl
and SpecializedAccountServiceImpl
.
假设我需要依赖Spring bean 的几种实现。我有一个AccountService
接口和两个实现:DefaultAccountServiceImpl
和SpecializedAccountServiceImpl
.
How is this possible (injecting one or the other implementation) in Spring?
Which implementation will the following injection use?
@Autowired private AccountService accountService;
这在 Spring 中怎么可能(注入一个或另一个实现)?
以下注入将使用哪种实现?
@Autowired private AccountService accountService;
回答by Tomasz Nurkiewicz
Ad. 1: you can use @Qualifier
annotationor autowire using @Resource
as opposed to @Autowired
which 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/