4

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Diamond
  • 217
  • 1
  • 3
  • 7
  • Possible duplicate of [What is the difference between spring factory-method and factory-bean?](https://stackoverflow.com/questions/18772490/what-is-the-difference-between-spring-factory-method-and-factory-bean) – pvpkiran Feb 03 '18 at 08:27

1 Answers1

3

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
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • Should this factory method usually produce prototype or singleton beans? – Diamond Feb 03 '18 at 15:47
  • @Diamond, I believe we can produce an any-scoped bean in this way – Andrew Tobilko Feb 03 '18 at 16:19
  • @Diamond, All the scopes have the stage where a bean is initialised at. You specify only the way it's going to be constructed. No much difference between a constructor and a static method here. Is that helpful? – Andrew Tobilko Feb 04 '18 at 13:03