Java 处理一个Springbean/接口的多个实现

Java 处理一个Springbean/接口的多个实现,java,spring,interface,Java,Spring,Interface,假设我需要依赖Springbean的几个实现。我有一个AccountService接口和两个实现:DefaultAccountServiceImpl和SpecializedAccountServiceImpl 在Spring中,这怎么可能(注入一个或另一个实现) 以下注入将使用哪个实现 @Autowired private AccountService accountService; 广告1:您可以使用@Resource或autowire,而不是默认为字段名而不是类型的@Autowired

假设我需要依赖Springbean的几个实现。我有一个
AccountService
接口和两个实现:
DefaultAccountServiceImpl
SpecializedAccountServiceImpl

  • 在Spring中,这怎么可能(注入一个或另一个实现)

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

    @Autowired
    private AccountService accountService;
    
  • 广告1:您可以使用
    @Resource
    或autowire,而不是默认为字段名而不是类型的
    @Autowired


    广告2:它将在运行时失败,因为有两个bean正在实现这个接口。如果您的一个bean是额外的,那么在按类型自动连接时,它将是首选。

    Tomasz:我知道我需要使用
    @Qualifier(“专用”)
    来指定要注入的实现。那么,如果我使用java(而不是xml)定义我的服务,我如何指定它具有哪个限定符?这行吗:
    @Service(“specialized”)
    ?@balteo:行。要么在
    @service
    注释中手动分配服务名称,要么使用第一个小写字符的简单类名:
    @Qualifier(“specializedAccountServiceImpl”)
    。如果我想切换接口自动连接的所有位置的实现,该怎么办?我不想在所有使用位置都显式指定。您可以使用@value使用Spring表达式,并将该值放入属性文件(application.properties)中,然后来回切换限定符。(我还没有在这个特殊的例子中尝试过这个方法,但我确信注释所使用的只是一个字符串,所以它应该可以正常工作。
    @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/