问题描述
说我需要依赖Spring的几个实现。我有一个 AccountService
接口和两个实现: DefaultAccountServiceImpl
和 SpecializedAccountServiceImpl
。
Say I need to rely on several implementations of a Spring bean. I have one AccountService
interface and two implementations: DefaultAccountServiceImpl
and SpecializedAccountServiceImpl
.
-
这怎么可能(注入一个或另一个实现)在Spring?
How is this possible (injecting one or the other implementation) in Spring?
以下注入使用哪种实现?
Which implementation will the following injection use?
@Autowired
private AccountService accountService;
推荐答案
广告。 1:你可以使用或使用 @Resource
进行自动装配,而不是 @自动装配
,默认为字段名称而不是类型。
Ad. 1: you can use @Qualifier
annotation or autowire using @Resource
as opposed to @Autowired
which defaults to field name rather than type.
广告。 2:它将在运行时失败,说两个bean正在实现此接口。如果您的其中一个bean另外进行注释,在按类型自动装配时将首选。
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.
这篇关于处理一个Spring bean /接口的几个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!