Static factory method (Spring)

What is the advantage and use for creating bean in Spring Framework using static factory method?

+4
source share
2 answers

The benefits of using the static factory method to create a bean do not necessarily come from Spring, which is just an IoC container.

Some suggestions Effective Java Idiom # 1, which provides a static factory, provides the following advantages over creating objects from the constructor:

  • Gives your methods a more expressive name than a constructor.
  • You can skip creating the actual object and provide a proxy.
  • You can return a subtype of the return type of the method.

I find the biggest advantage of this idiom in the name of methods with similar signatures.

for example, if you have:

Person { String name; String[] booksAuthored; //... constructors, getters, setters } 

Then you can create instances by calling them:

 Person joshTheProgrammer = Person.createByName("Joshua Bloch"); 

or

 Person joshTheAuthor = Person.createByBookName("Effective Java"); 

you cannot do this when using constructors, since you can only have one constructor that accepts a string.

+7
source

I would like to add the fact that perhaps some third-party libraries simply rely on factory methods. Therefore, you probably do not want (or even cannot) change the code, which will be just compatible with DI. Thus, in this case, you can integrate legacy code with dependency injection, although it was not intended to be used in such a scenario initially.

0
source

Source: https://habr.com/ru/post/1305090/


All Articles