Wednesday 8 February 2017

Spring: Instantiating beans with static factory method

 ‘factory-method’ attribute of bean tag is used to define a bean using static factory method. Specify the factory method name as value to the attribute ‘factory-method’.

Syntax
<bean id="beanId" class="className" factory-method="factoryMethodName"/>

Example
<bean id="shape" name="shape" class="com.sample.pojo.ShapeFactory" 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");
 }
}

ShapeFactory.java
package com.sample.pojo;

public class ShapeFactory {

 public static 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="shape" name="shape" class="com.sample.pojo.ShapeFactory"
  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


You can also pass arguments to static factory method, my next posts explain this.







Previous                                                 Next                                                 Home

No comments:

Post a Comment