'How to import a spring application context into another application context?

I have two spring application contexts. One is local to my application and the other is from one of the maven dependencies.

Now, my applicationContext.xml file look like this.

<import resource="classpath*:**/sample-applicationContext.xml" />

and I have <context:component-scan> in the sample-applicationContext.xml file which scans for components.

and Now, when I do the following..

ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
MyClass m=ctx.getBean(MyClass.class);

Unfortunately, when I get the MyClass object, the object is created however, I see that dependencies in MyClass are not injected.

The dependencies autowired in MyClass are the beans that are scanned using the <context:component-scan> in sample-applicationContext.xml file.

Is there any way to make use of multiple application contexts present in the Maven dependencies and autowire beans in them in my project classes?



Solution 1:[1]

I'm not sure about maven dependencies, but you are trying to do something like a cross-context using spring. Take a look at this link: http://blog.imaginea.com/cross-context-communication-between-web-applications/

EDIT: it seems there is a way, take a look at this post: Loading spring application context files that are inside a jar in classpath

Solution 2:[2]

the following way, you can load the multiple spring applicationContext files.

ApplicationContext context = 
new ClassPathXmlApplicationContext(new String[] {"sample-applicationContext.xml",   "applicationContext.xml"});

it will be good if you can post the applicationContext.xml , sample-applicationContext.xml and MyClass code segments here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Chathuranga Tennakoon