Just Load the XML file and create the application context object. As long as XML is loaded, Spring will inject all the object dependencies.
So, You don't need to load or create application context object again and again. Just check your console with the below example, you will understand it.
Example: In main method you only write this line of code.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
interface IParent {
public void whoAreYou();
}
class ChildA implements IParent {
public ChildA (IParent ChildB) {
super();
System.err.println("Constructor ChildA ");
ChildB.whoAreYou();
}
public ChildA (){
System.err.println("Constructor ChildA ");
}
@Override
public void whoAreYou() {
System.err.println("ChildA ");
}
}
class ChildB implements IParent {
public ChildB (){
System.err.println("Constructor ChildB");
}
@Override
public void whoAreYou() {
System.err.println("ChildB");
}
}
XML File :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<context:annotation-config/>
<bean id="childA" class="com.spring.xmlbased.config.ChildA">
<constructor-arg>
<bean id="ChildB" class="com.spring.xmlbased.config.ChildB"/>
</constructor-arg>
</bean>
</beans>
Please let me know, if u need further clarification.