What's the reason to instantiate Spring beans with factory methods?

时间:2018-02-03 08:09:52

标签: spring dependency-injection static-factory

I know there are constructor-based injection and setter-based injection in Spring. When should I use factory methods to inject beans?

1 个答案:

答案 0 :(得分:2)

It's rather a design matter and depends on your architecture.

If you have classes with static factory methods, why should you add unnecessary constructors breaking the design just to fit a DI framework?

It's inflexible, thus Spring supports both ways.


Excerpt from Joshua Bloch “Effective Java”:

Item 1: Consider static factory methods instead of constructors.

Static factory methods advantages:

  • They have names.
  • They are not required to create a new object each time they are invoked.
  • They can return an object of any subtype of their return type.
  • They reduce verbosity of creating parameterized type instances.

Static factory methods disadvantages:

  • When providing only static factory methods, classes without public or protected constructors cannot be subclassed.
  • They are not readily distinguishable from other static methods