Spring FactoryBean

While working on a Spring application, I noticed that there was a type discrepancy between the bean declaration in the application context and the class type of the to-be-injected property in Java.

The velocityEngine bean declared in the application context was of type VelocityEngineFactoryBean.

    <bean id="velocityEngine" 
        class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
        <property name="resourceLoaderPath" value="/email_templates/"/>
    </bean>

While setVelocityEngine() of the Java class accepts an object of type VelocityEngine.

import org.apache.velocity.app.VelocityEngine;

@Component
public class Emailer {

    private VelocityEngine velocityEngine;

    @Autowired
    public void setVelocityEngine(VelocityEngine velocityEngine) {
        this.velocityEngine = velocityEngine;
    }
}

As it turns out, the FactoryBean is Spring’s way of instantiating more complex objects. To properly create a FactoryBean, a class must implement org.springframework.beans.factory.FactoryBean<T>. There are 3 methods of note in this interface:

  • T getObject() should return an instance of the object. For the case of the example above, this is an instance of VelocityEngine
  • Class<?> getObjectType() should return the type of the object that will be created by the FactoryBean. This can be null if the type is not known in advance.
  • boolean isSingleton() should return true if there should only be one copy of the object. This allows Spring to cache the instance of the created object.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s