1.8.3. Customizing Instantiation Logic with a FactoryBean
You can implement the org.springframework.beans.factory.FactoryBean
interface for objects that are themselves factories.
The FactoryBean
interface is a point of pluggability into the Spring IoC container’s instantiation logic. If you have complex initialization code that is better expressed in Java as opposed to a (potentially) verbose amount of XML, you can create your own FactoryBean
, write the complex initialization inside that class, and then plug your custom FactoryBean
into the container.
The FactoryBean
interface provides three methods:
Object getObject()
: Returns an instance of the object this factory creates. The instance can possibly be shared, depending on whether this factory returns singletons or prototypes.boolean isSingleton()
: Returnstrue
if thisFactoryBean
returns singletons orfalse
otherwise.Class getObjectType()
: Returns the object type returned by thegetObject()
method ornull
if the type is not known in advance.
The FactoryBean
concept and interface is used in a number of places within the Spring Framework. More than 50 implementations of the FactoryBean
interface ship with Spring itself.
When you need to ask a container for an actual FactoryBean
instance itself instead of the bean it produces, preface the bean’s id
with the ampersand symbol (&
) when calling the getBean()
method of the ApplicationContext
. So, for a given FactoryBean
with an id
of myBean
, invoking getBean("myBean")
on the container returns the product of the FactoryBean
, whereas invoking getBean("&myBean")
returns the FactoryBean
instance itself.