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:

SampleBean.java

StaticMethodFactory.java

NonStaticMethodFactory.java

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:

Testing:
Create a simple Application Context file:

Result:

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

Result:

II. Sourcecode

SpringFactoryMethod


Related Posts


Got Something To Say:

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

*