Using instance factory method

Instance creation is done through a non static method of a bean. To use the method for instance creation, an attribute factory-method has to be configured. Sometimes, some other class may also be used to create the instance. The factory-bean attribute will be configured along with the factory-method attribute to be used by the container for instance creation.

Let's follow these steps to use factory-method for instance creation. We will use the same Ch02_Instance_Creation instance.

  1. Create a CarFactory class in the com.ch02.factory package, as shown in the following piece of code:
public class CarFactory { 
  private static Car car=new Car(); 
 
  public Car buildCar() 
  { 
    System.out.println("building the car "); 
    return car; 
  } 
} 

The buildCar() method will build an instance of Car, and return it. Now, the task of making the container aware of using the preceding code will be done by the bean definition.

  1. In the instance.xml file, add two beans--one bean for CarFactory, and one for Car, as shown in the following lines of code:
<bean id="car_factory" class="com.ch02.factory.CarFactory"/> 
<bean id="car_obj_new" factory-bean="car_factory" 
factory-method="buildCar" /> 

The factory-method attribute specifies buildCar as the method that is to be used from car_factory, which is specified by the factory-bean attribute to be used for instance creation. No need to specify the class attribute here.

  1. Create Test_CarFactory with the main function using the following code:
public static void main(String[] args) { 
  // TODO Auto-generated method stub 
  ApplicationContext context = new 
    ClassPathXmlApplicationContext("instance.xml"); 
  Car car = (Car) context.getBean("car_obj_new"); 
  car.show(); 
} 
  1. On execution, the following screenshot will be shown:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.178.133