We will use the same project Ch02_Dependency_Injection with the help of the following steps:
- Add a parameterized constructor to Car, which has the following code:
public Car(String chassis_number, String color,
double average, long price, String fuel_type) { // TODO Auto-generated constructor stub this.chassis_number = chassis_number; this.average = average; this.price = price; this.color=color; this.fuel_type=fuel_type; }
If you add a parameterized constructor, and you want to use both setter as well as constructor injection, you must add a default constructor.
- Add one more bean in the beans.xml file but, this time, instead of using the <property> tag, we will use <constructor-arg> to use the constructor DI. The code will look like this:
<bean id="car_const" class="com.ch02.beans.Car"> <constructor-arg value="eng023"></constructor-arg> <constructor-arg value="green"></constructor-arg> <constructor-arg value="12"></constructor-arg> <constructor-arg value="678900"></constructor-arg> <constructor-arg value="petrol"></constructor-arg> </bean>
- Create a TestCarConstructorDI class in the default package, which will take the Car object from the container. The code will be as follows:
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml"); Car car=(Car)context.getBean("car_const"); car.show(); }
- Execute the code, and the bean values will be displayed on the console.
Here, the container is happy to have each parameter of the constructor with a distinguished data type. However, this is not the same case every time. Many times, occurrence of multiple constructors leads to confusion while setting up the properties. Let's see how.