[英]Java - Spring: dependency injection across bean factories in SingletonBeanFactoryLocator?
I have the following scenario: 我有以下情况:
1) two xml configuration files, say foo.xml
and bar.xml
. 1)两个xml配置文件,分别是foo.xml
和bar.xml
。 They contain ClassPathXmlApplicationContext
beans with names fooFactory
and barFactory
resp. 它们包含名称分别为fooFactory
和barFactory
ClassPathXmlApplicationContext
bean。 Each bean in turn is given its own xml configuration file through its constructor, 每个Bean都会通过其构造函数获得自己的xml配置文件,
2) client code uses SingletonBeanFactoryLocator
and methods getInstance
and useBean
to get these factories. 2)客户端代码使用SingletonBeanFactoryLocator
和方法getInstance
和useBean
来获取这些工厂。 Eg SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");
例如SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");
Requirement: some beans in barFactory need to access some beans in fooFactory. 要求:barFactory中的某些bean需要访问fooFactory中的一些bean。
The current solution is to get a reference to fooFactory through SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");
当前的解决方案是通过SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");
获得对fooFactory的引用SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");
and the use getBean
to get the necessary beans. 并使用getBean
获得必需的bean。
Question: is it possible to inject beans from fooFactory
into beans from barFactory
, so beans in barFactory
get these dependencies automatically? 问:是否有可能以将来自豆fooFactory
成从豆类barFactory
,因此在豆类barFactory
自动获取这些依赖?
Why don't you have a "common" application context xml. 为什么没有“公共”应用程序上下文XML。
In this file, you can define beans that will be used in both foo and bar. 在此文件中,您可以定义将在foo和bar中使用的bean。 Then you can import this common xml in to both the application contexts. 然后,您可以将此通用xml导入到两个应用程序上下文中。
This approach would create those beans defined in the common xml twice, but this may or may not be a problem. 这种方法将两次创建在通用xml中定义的bean,但这可能是,也可能不是问题。 If you want to share the SAME instances you could create the common beans as Singletons. 如果要共享SAME实例,则可以将公共bean创建为Singletons。
I ended up defining these factories in the same .xml and chaining them. 我最终在相同的.xml中定义了这些工厂并将它们链接起来。 I then did normal injection of fooFactory beans into barFactory beans. 然后,我将fooFactory bean正常注入了barFactory bean中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.