简体   繁体   中英

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 . They contain ClassPathXmlApplicationContext beans with names fooFactory and barFactory resp. Each bean in turn is given its own xml configuration file through its constructor,

2) client code uses SingletonBeanFactoryLocator and methods getInstance and useBean to get these factories. Eg SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory");

Requirement: some beans in barFactory need to access some beans in fooFactory.

The current solution is to get a reference to fooFactory through SingletonBeanFactoryLocator.getInstance("classpath:foo.xml").useBeanFactory("fooFactory"); and the use getBean to get the necessary beans.

Question: is it possible to inject beans from fooFactory into beans from barFactory , so beans in barFactory get these dependencies automatically?

Why don't you have a "common" application context xml.

In this file, you can define beans that will be used in both foo and bar. Then you can import this common xml in to both the application contexts.

This approach would create those beans defined in the common xml twice, but this may or may not be a problem. If you want to share the SAME instances you could create the common beans as Singletons.

I ended up defining these factories in the same .xml and chaining them. I then did normal injection of fooFactory beans into barFactory beans.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM