处理一个 Spring bean/接口的多个实现 [英] Handling several implementations of one Spring bean/interface

查看:31
本文介绍了处理一个 Spring bean/接口的多个实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

  1. 这在 Spring 中怎么可能(注入一个或另一个实现)?

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

以下注入将使用哪个实现?

Which implementation will the following injection use?

@Autowired
private AccountService accountService;

推荐答案

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

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 是另外 @Primary 注释,按类型自动装配时优先使用.

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/接口的多个实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆