【问题标题】:Handling several implementations of one Spring bean/interface处理一个 Spring bean/接口的多个实现
【发布时间】:2012-08-02 12:06:49
【问题描述】:

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

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

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

    @Autowired
    private AccountService accountService;
    

【问题讨论】:

    标签: java spring interface


    【解决方案1】:

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

    广告。 2:它会在运行时失败,说两个 bean 正在实现这个接口。如果您的 bean 之一另外是 annotated with @Primary,则在按类型自动装配时将首选它。

    【讨论】:

    • Tomasz:我知道我需要使用@Qualifier("specialized") 来指定将要注入的实现。然后,如果我使用 java(而不是 xml)定义我的服务,我该如何指定它具有哪个限定符?这样做可以:@Service("specialized")
    • @balteo:是的。在 @Service 注释中手动分配服务名称,或者采用第一个字符小写的简单类名称:@Qualifier("specializedAccountServiceImpl")
    【解决方案2】:
    @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/
    

    【讨论】:

    • 如果我想为我@Autowire 接口的所有地方切换实现怎么办?我不想在所有使用场所明确指定。
    • 您可以使用 @value 使用 Spring 表达式并将值放入属性文件 (application.properties) 并来回切换 bean 限定符。 (在这种特殊情况下我没有尝试过,但我确信它只是注释正在使用的字符串,所以它应该可以正常工作。
    猜你喜欢
    • 2015-10-09
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2019-09-03
    • 1970-01-01
    • 1970-01-01
    • 2014-01-24
    相关资源
    最近更新 更多