Tuesday 14 February 2017

Spring: Instantiate bean using an instance factory method

In my previous post, I explained how to define a bean using static factory method. In this post, I am going to explain how to instantiate bean using instance factory method.

First step is, you need to define a factory bean.

<bean id="shapeFactoryBean" class="com.sample.pojo.ShapeFactory" />

By specifying the factory-bean and factory-method, you can instantiate a bean.

<bean id="shape" name="shape" factory-bean="shapeFactoryBean" factory-method="getShape" />

Following is the complete working application.

Shape.java
package com.sample.pojo;

public class Shape {

 public void draw(){
  System.out.println("Drawing shape");
 }
}

ShapFactory.java
package com.sample.pojo;

public class ShapeFactory {

 public Shape getShape(){
  return new Shape();
 }
}


myConfiguration.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="shapeFactoryBean" class="com.sample.pojo.ShapeFactory" />

 <bean id="shape" name="shape" factory-bean="shapeFactoryBean"
  factory-method="getShape" />

</beans>

HelloWorld.java
package com.sample.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.sample.pojo.Shape;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Shape shape = (Shape) context.getBean("shape");
  
  shape.draw();

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.


Drawing shape







Previous                                                 Next                                                 Home

No comments:

Post a Comment