Spring@Autowire未在ApplicationContext中定义的同一类的两个bean
我正在开发SpringMVC应用程序,遇到了一个问题。我是春天的新手,所以如果我的工作有点笨拙,请原谅我。基本上我有一个java类ContractList。在我的应用程序中,我需要这个类的两个不同对象(它们都必须是singleton)Spring@Autowire未在ApplicationContext中定义的同一类的两个bean,spring,dependency-injection,autowired,Spring,Dependency Injection,Autowired,我正在开发SpringMVC应用程序,遇到了一个问题。我是春天的新手,所以如果我的工作有点笨拙,请原谅我。基本上我有一个java类ContractList。在我的应用程序中,我需要这个类的两个不同对象(它们都必须是singleton) 请注意,ApplicationContext.xml中没有定义这两个bean。我只使用注释。因此,当我试图访问它们时,contractList和correctContractList最终指向同一个对象。有没有一种方法可以在不在ApplicationContext.
请注意,ApplicationContext.xml中没有定义这两个bean。我只使用注释。因此,当我试图访问它们时,contractList和correctContractList最终指向同一个对象。有没有一种方法可以在不在ApplicationContext.xml中明确定义它们的情况下以某种方式区分它们 您可以为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>
如果您无法访问用
@Autowired
注释的类,您可以做另一件事。如果星星对你有利,你也许可以利用@Primary
注释
假设您有一个无法修改的库类:
class LibraryClass{
@Autowired
ServiceInterface dependency;
}
还有另一个你可以控制的类:
这样设置您的配置,它应该可以工作:
@Bean
@Primary
public ServiceInterface libraryService(){
return new LibraryService();
}
@Bean
public ServiceInterface myService(){
return new MyService();
}
并用Qualifier
注释MyClass
,告诉它使用myService
LibraryClass
将使用带有@Primary
注释的bean,MyClass
将使用此配置的另一个bean:
class MyClass{
@Autowired
@Qualifier("myService")
ServiceInterface dependency;
}
这是一个罕见的用法,但我使用它的情况是,我有自己的类,需要使用旧实现和新实现。谢谢!我并不是在避免使用xml定义。。。我很好奇,如果没有xml中的显式定义,是否有办法做到这一点。没问题。如果答案解决了你的问题,请把它标为正确答案。
@Bean
@Primary
public ServiceInterface libraryService(){
return new LibraryService();
}
@Bean
public ServiceInterface myService(){
return new MyService();
}
class MyClass{
@Autowired
@Qualifier("myService")
ServiceInterface dependency;
}