In this example, we will see how you make dependency with the XML configuration file. First I am going to create the class Car
withe dependancy Engine
.
So your Car
class would be like this
package com.kayak; public class Car { Engine engine; private String name; public Car() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setEngine(Engine engine) { System.out.println("Inside setEngine()"); this.engine = engine; } Car(Engine engine) { System.out.println("Inside Car Constrsctor"); this.engine = engine; } }
This is the dependant class Engine
package com.kayak; public class Engine { Engine(){ System.out.println("Engine Created"); } }
Next you can create the configuration file bean.xml
When you look at the XML file you can see the I have created the
withe ref
which points to bean having the id with engine. So we tell to spring that Engine
is dependant class of the Car
class
Now we can create the bean using context
package springstrat; import com.kayak.Car; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringStrat { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); Car car=(Car)ctx.getBean("car"); System.out.println(car.getName()); } }
When you run the application you can see the following output
run: Feb 15, 2018 5:09:58 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date [Thu Feb 15 17:09:58 IST 2018]; root of context hierarchy Feb 15, 2018 5:09:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [bean.xml] Engine Created Inside setEngine() Audi BUILD SUCCESSFUL (total time: 2 seconds)
Alternatively, you can use the followng configuration file