【问题标题】:Spring @Autowire two beans of the same class which are not defined in ApplicationContextSpring @Autowire 两个未在 ApplicationContext 中定义的相同类的bean
【发布时间】:2013-03-20 06:29:29
【问题描述】:

我正在开发 Spring MVC 应用程序并遇到问题。我是Spring新手,所以如果我的工作有点笨拙,请原谅我。基本上我有一个java类ContractList。在我的应用程序中,我需要这个类的两个不同对象(它们都必须是单例的)

public class MyClass {
    @Autowired
    private ContractList contractList;

    @Autowired
    private ContractList correctContractList;

    .. do something..
}

请注意,这两个 bean 都没有在 ApplicationContext.xml 中定义。我只使用注释。因此,当我尝试访问它们时 - contractList 和 correctContractList 最终引用了同一个对象。有没有办法以某种方式区分它们而不在 ApplicationContext.xml 中明确定义它们?

【问题讨论】:

    标签: spring dependency-injection autowired


    【解决方案1】:

    您可以为 bean 提供限定符:

    @Service("contractList")
    public class DefaultContractList implements ContractList { ... }
    
    @Service("correctContractList")
    public class CorrectContractList implements ContractList { ... }
    

    并像这样使用它们:

    public class MyClass {
    
        @Autowired
        @Qualifier("contractList")
        private ContractList contractList;
    
        @Autowired
        @Qualifier("correctContractList")
        private ContractList correctContractList;
    }
    

    在 xml 配置中仍然使用 @Autowired 这将是:

    <beans>
        <bean id="contractList" class="org.example.DefaultContractList" />
        <bean id="correctContractList" class="org.example.CorrectContractList" />
    
        <!-- The dependencies are autowired here with the @Qualifier annotation -->
        <bean id="myClass" class="org.example.MyClass" />
    </beans>
    

    【讨论】:

    • 谢谢!这不像我在避免使用 xml 定义......我很好奇是否有一种方法可以在没有 xml 中明确定义的情况下这样做。
    • 没问题。如果它解决了您的问题,请标记答案正确。
    【解决方案2】:

    如果您无权访问带有@Autowired 注释的类,您可能还可以做另一件事。如果星星对齐对您有利,您也许可以利用 @Primary 注释。

    假设您有一个无法修改的库类:

    class LibraryClass{
       @Autowired
       ServiceInterface dependency; 
    }
    

    还有另一个你控制的类:

    class MyClass{
       @Autowired
       ServiceInterface dependency; 
    }
    

    像这样设置你的配置,它应该可以工作:

    @Bean
    @Primary
    public ServiceInterface libraryService(){
      return new LibraryService();
    }
    
    @Bean
    public ServiceInterface myService(){
      return new MyService();
    }
    

    并用Qualifier 注释MyClass 以告诉它使用myServiceLibraryClass 将使用带有 @Primary 注释的 bean,MyClass 将在此配置中使用另一个:

    class MyClass{
       @Autowired
       @Qualifier("myService")
       ServiceInterface dependency; 
    }
    

    这是一种罕见的用途,但我在我有自己的类需要使用旧实现和新实现的情况下使用它。

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-26
      • 2016-03-03
      • 1970-01-01
      • 2019-09-03
      相关资源
      最近更新 更多