I am new Springs. In Bean tag I found factory-method and factory-bean Attributes. What is the difference between factory-method and factory-bean?
I am using factory-method to call my getInstance static method to create singleton object.
What is factory-bean used for?
For given replies, What I understood was
Factory-method is used for calling a static method to create object in same bean class.
Factory-bean is used for creating a object based on factory design pattern.
Ex:- I am asking a EggPlant object from VegetableFactory (Which will return vegetable object which was asked)class by passing my vegetable name(EggPlant in this case).
Please correct if I am wrong?
It's basically the same difference between the Factory method and Factory design patterns, with a little note at the bottom. While one is a method used to obtain instances of a specific class, the other is a full fledged object responsible of creating objects, including all of the required logic to do so.
FactoryBean
's interface documentation states:
Interface to be implemented by objects used within a BeanFactory which are themselves factories. If a bean implements this interface, it is used as a factory for an object to expose, not directly as a bean instance that will be exposed itself.
Also, this object is not used as a bean instance, but as an instance provider through its getObject
method.
Searching for uses of factory-method
over a FactoryBean
, it seems that it used quite oftenly with legacy singleton beans, to get the underlying instance, but this approach doesn't provide support for initialization methods, such as, for example, an init
method that initializes a given set of properties.
In this case, you either have to invoke it yourself before using the class, define a wrapper that handles the initialization or make use of other mechanisms such as MethodInvokingFactoryBean
.
Strictly speaking, a FactoryBean
is intended to manage a specific type. You'd have, in fact, an EggPlantFactory
, not a VegetableFactory
since the getObject
method defined by the FactoryBean
interface doesn't support parameters.