Good Evening Folks.

Today we will deal with a situation where we need an Object in our Spring bean class which can not be created with normal spring bean configuration tag.

Lets take a example where requirement is we need inject an object inside my spring bean and here is class.

  public class MyBean {
    // Other properties 

	private Calendar Calendar;

	public Calendar getCalendar() {
		return Calendar;
	}

	public void setCalendar(Calendar calendar) {
		Calendar = calendar;
	}	
}

and the configuartion file is.

 <bean id="bean" class="com.jft.user.MyBean">
        <property name="calendar" ref="calendar"></property>
 </bean>
  
  <bean id="calendar" class="java.util.Calendar"></bean>
  

by looking at above configuration seems easy with spring ioc injection. but here is the problem the calendar class object can not be created using new operator

   ex. Calendar calendar=new Calendar()
 

but in java this is possible only through static factory method.

	ex. Calendar calendar=Calendar.getInstance()
 

So we can’t define Spring bean tag to create calendar class object like this

    <bean id="calendar" class="java.util.Calendar"></bean>

Then how to inject Calendar class instance in spring bean….?

Solution

Spring framework provieds one Attribute at tag level to define This bean should be created using static factory method only.

Here is the configuration file.

  
  <bean id="calendar" class="java.util.Calendar" factory-method="getInstance"></bean>

By adding the factory-method Spring will take care of creating object using static factory method.

Hope this helps. Thanks