How to use Spring Factory Method to create Spring Bean

Spring Framework provides Spring Factory Method mechanics to create Beans from static(non-static) method of a Factory Class in XML config files. In the tutorial, JavaSampleApproach will introduce Spring Factory Method with sample codes.

Related Posts:
How to inject Collection in Spring
Inject Properties from Properties File using Spring Environment

0. Preparation

Create a POJO bean class & 2 factory classes with static & non-static factory methods for the tutorial:

I. Spring Factory Method

Question: How to configure a SampleBean from each factories: StaticMethodFactory & NonStaticMethodFactory?

1. With Java Config

We have a solution with very simple configuration:

Create a simple Application Context file:


2. Use Spring Factory Method with XML config

Case 1: With Static Method Factory like StaticMethodFactory class.
Use: factory-method to indicate the method name of the Factory class.
constructor-arg is used to specify arguments of the factory method.

Case 2: With Non-Static Method Factory like NonStaticMethodFactory class.
Need declare an additional factory bean: NonStaticMethodFactory, then use factory-bean to indicate it.

Testing: create a simple application context file


II. Sourcecode


Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *