What is the advantage and use to Instantiate a bean in Spring Framework using a static factory method?
The advantages of using the static factory method for bean instantiation don't necessarily come from Spring which is just an IoC container.
Some suggestions from Effective Java Idiom#1, providing static factory provides the following advantages over creating objects from constructor:
- Gives your methods a more expressive name, than the Constructor.
- You can, skip actual object creation and provide proxies.
- You can return a subtype of the method return type.
I find the greatest advantage of this idiom in having named methods with similar signatures.
for example if you have:
Person {
String name;
String[] booksAuthored;
//... constructors, getters, setters
}
Then you can create instances by calling these:
Person joshTheProgrammer = Person.createByName("Joshua Bloch");
or
Person joshTheAuthor = Person.createByBookName("Effective Java");
you can't do that when using the constructors, as you can have only one constructor that accepts a String.
I'd like to add the fact that maybe some thirdparty libraries simply rely on using factory methods. So you probably don't want (or even can't) change the code to be simply DI compatible. So in this case you can integrate legacy code with dependency injection although it was not designed to be used in such a scenarion initially.