5

我正在开发 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 中明确定义它们?

4

2 回答 2

9

您可以为 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>
于 2013-03-20T06:33:08.760 回答
1

如果您无权访问带有注释的类,@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();
}

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

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

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

于 2018-12-18T21:44:27.487 回答