2

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
  • Add example of your code Commented Dec 10, 2013 at 9:25
  • still no answer to this question? Commented Jan 8, 2016 at 6:04

2 Answers 2

4

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"/>
Sign up to request clarification or add additional context in comments.

4 Comments

class="YourFactoryClass" shouldnt this be the name of the class whose instance needs to be created?
@varun you're right, that works if the static factory method is on the class itself, I'll update the answer.
what if static factory method is not on the class itself, its inside some other class
I really dont want my factory to be a bean itself.
1

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

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

1 Comment

I already know how it can be done if I create bean of my factory class, but i dont want to create any instance of my factory class. Lets say my factory class is abstract.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.