Backend Development 7 min read

Master Spring’s FactoryBean: From Basics to Advanced Use Cases

This article explains Spring's FactoryBean interface, detailing its three core methods, and provides step‑by‑step examples—including a simple bean, prototype scope, proxy creation, accessing the original FactoryBean, and using ServiceFactoryBean for SPI—illustrating how to customize bean instantiation in Spring 6.

Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Spring Full-Stack Practical Cases
Master Spring’s FactoryBean: From Basics to Advanced Use Cases

Environment: Spring 6.1.7

1. Introduction

The FactoryBean interface is an extension point of the Spring IoC container that lets you replace XML‑based bean definitions with Java code for complex initialization logic. By implementing a custom FactoryBean you can create and configure objects programmatically and register them in the container.

FactoryBean<T> defines three methods:

T getObject() : Returns the instance created by the factory. The instance may be shared depending on whether the factory is a singleton or prototype.

boolean isSingleton() : Indicates whether the object returned by getObject() should be a singleton (default true ).

Class<?> getObjectType() : Returns the type of object that getObject() produces, or null if the type is not known in advance.

Spring itself provides more than 50 built‑in implementations of FactoryBean. The following sections demonstrate common usage patterns.

2. Practical Examples

2.1 Simple Example

Define a custom FactoryBean that creates a PersonService instance.

<code>@Component
public class PersonServiceFactoryBean implements FactoryBean&lt;PersonService&gt; {
    @Override
    public PersonService getObject() throws Exception {
        return new PersonService();
    }
    @Override
    public Class&lt;?&gt; getObjectType() {
        return PersonService.class;
    }
    @Override
    public boolean isSingleton() {
        return true;
    }
}
</code>

Usage:

<code>// Direct injection in another bean
@Resource
private PersonService personService;

// Manual retrieval from the container
ApplicationContext context = ...;
PersonService ps = context.getBean(PersonService.class);
</code>

2.2 Prototype (Non‑Singleton) and No Type

To obtain a new instance on each request, return false from isSingleton() :

<code>@Override
public boolean isSingleton() {
    return false;
}
</code>

When getObjectType() returns null , Spring cannot determine the bean type for injection, and an exception will be thrown.

2.3 Creating a Proxy with FactoryBean

Use ProxyFactory inside getObject() to return a proxied instance.

<code>@Override
public PersonService getObject() throws Exception {
    ProxyFactory factory = new ProxyFactory();
    factory.setTarget(new PersonService());
    factory.addAdvice(new MethodInterceptor() {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            System.out.println("before...");
            return invocation.proceed();
        }
    });
    return (PersonService) factory.getProxy();
}
</code>

2.4 Accessing the Original FactoryBean

To retrieve the FactoryBean itself rather than the object it creates, use either the bean type or prefix the bean name with &amp; :

<code>// By type
PersonServiceFactoryBean factoryBean = context.getBean(PersonServiceFactoryBean.class);

// By name with '&' prefix
PersonServiceFactoryBean factoryBean2 = (PersonServiceFactoryBean) context.getBean("&psFactoryBean");
</code>

2.5 Using ServiceFactoryBean for SPI

Spring provides ServiceFactoryBean to load implementations of a service interface via the Java SPI mechanism.

<code>@Configuration
public class AppConfig {
    @Bean
    public ServiceFactoryBean serviceFactoryBean() {
        ServiceFactoryBean fb = new ServiceFactoryBean();
        fb.setServiceType(DAO.class);
        return fb;
    }
}
</code>

Place a file named com.example.DAO under META-INF/services containing the fully‑qualified class names of the implementations (e.g., com.pack.bean.create.PersonDAO , com.pack.bean.create.StudentDAO ). When DAO is injected, Spring will provide the first listed implementation. To obtain all implementations, use ServiceListFactoryBean .

Below is an illustration of the FactoryBean concept:

JavaProxySpringdependency injectionFactoryBeanSPI
Spring Full-Stack Practical Cases
Written by

Spring Full-Stack Practical Cases

Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.