Creating bean using static method from another class

5.5k Views Asked by At

I have a factory class which has various static methods to return the instances of some classes. How can a bean be created in spring using static factory method in different class?

something like:

public class InstanceFactory
{    
  public static JellyBean getJellyBeanInstance()
  {
    return new JellyBean(); 
  }
}

I need a JellyBean.

2

There are 2 best solutions below

4
On

Just change your getJellyBeanInstance() method to non-static, then you need:

<bean id="instanceFactory" class="InstanceFactory"/>

<bean id="yourBeanId" factory-bean="instanceFactory" factory-method="getJellyBeanInstance"/>
1
On

This should help: Spring Bean Instantiation with a static factory method

For instance factory method, next section from the document should help.