In Java, the following are the two ways to create an instance:
- Using constructor
- Using the factory method
I will not go into detailed scenarios on when to use which way, as we all are from Java background, and have read the reasons a number of times. We will directly start with how to use them in the Spring framework one by one. Hope that's fine with you!
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 thecom.ch02.beans
package withchassis_number
,color
,fuel type
,price
, andaverage
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()
inCar
as shown in the following lines of code:
public void show() { System.out.println("showing car "+chassis_number...