我正在开发 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 中显式定义它们?
您可以为 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;
}
在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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)