Spring @Autowire两个未在ApplicationContext中定义的相同类的bean [英] Spring @Autowire two beans of the same class which are not defined in ApplicationContext

查看:124
本文介绍了Spring @Autowire两个未在ApplicationContext中定义的相同类的bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on Spring MVC app and encountered a problem. I am new to Spring, so please forgive me if my working is a bit clumsy. Basically I have a java class ContractList. In my application I need two different objects of this class (both of them must be singleton)

public class MyClass {
    @Autowired
    private ContractList contractList;

    @Autowired
    private ContractList correctContractList;

    .. do something..
}

请注意,这两个bean均未在ApplicationContext.xml中定义.我只使用注释.因此,当我尝试访问它们时-contractList和correctContractList最终引用同一对象.是否有某种方法可以区分它们,而无需在ApplicationContext.xml中显式定义它们?

Note that both of these beans are not defined in ApplicationContext.xml. I am using only annotations. So when I try to access them - contractList and correctContractList end up referring to the same object. Is there a way to somehow differentiate them without defining them explicitly in ApplicationContext.xml ?

推荐答案

您可以给bean加上限定符:

You can give qualifiers to the beans:

@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;
}

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

In xml config still using @Autowired this would be:

<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>

这篇关于Spring @Autowire两个未在ApplicationContext中定义的相同类的bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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