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 answers

4
MattR 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
Atul On

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

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