Let's take an example of a Car to make it crystal clear how the container creates its object using the following steps:
- Create a Java application Ch02_Instance_Creation, and add jars that we added in the previous project.
- Create a Car class in the com.ch02.beans package with chassis_number, color, fuel type, price, and average as data members. The code is as follows:
class Car{ private String chassis_number, color, fuel_type; private long price; private double average;
}
- Add show() in Car as shown in the following lines of code:
public void show() { System.out.println("showing car "+chassis_number +" having color:-"+color+"and price:-"+price); }
- When the developer tries to create the object, the code will be as follows:
Car car_obj=new Car();
Now we need to configure BeanDefination in the XML file that represents a bean instance so that it will be managed by the Spring container.
Create instance.xml in Classpath to configure our Car BeanDefination; we will need to configure it as follows:
<bean id="car_obj" class="com.ch02.beans.Car"/> </beans>
- Create Test_Car with the main function in a default package to get the bean to use business logic as follows:
- Get a Spring container instance. We will use ClassPathXmlApplicationContext, as discussed in the container initialization.
- Get the bean instance from the container.
- Perform business logic using the bean instance.
The code will be as follows:
public class Test_Car { Public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("instance.xml"); Car car=(Car)context.getBean("car_obj"); car.show(); } }
- The output is as shown in the following screenshot:
It's pretty clear from the output that the container has used the default constructor to define the values. Let's prove it by adding a default constructor in Car by following this code:
public Car() { // TODO Auto-generated constructor stub chassis_number="eng00"; color="white"; fuel_type="diesel"; price=570000l; average=12d; }
The updated output is as shown in the following screenshot: