00:00

BeanFactoryPostProcessor in Spring

Last updated:

A BeanFactoryPostProcessor in Spring works one level earlier than almost everything else in the container: it runs after Spring has collected the bean definitions, the recipes for your beans, but before any ordinary bean has been created. That makes it the place to change recipes (switch a bean to lazy, change its scope, fill in placeholders) or to add new recipes based on configuration. Spring itself uses it to process @Configuration classes and to resolve ${...} placeholders.

This tutorial explains bean definitions, compares BeanFactoryPostProcessor with BeanPostProcessor, and builds two processors: one that modifies existing definitions and one that registers a bean per configured payment provider. It then shows the simpler Spring Framework 7 alternative, BeanRegistrar, and the rules that keep these early processors from breaking your application.

1. What Is a BeanFactoryPostProcessor?

BeanFactoryPostProcessor (org.springframework.beans.factory.config) is a functional interface with one method:

BeanFactoryPostProcessor.java
@FunctionalInterface
public interface BeanFactoryPostProcessor {

    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;
}

During the context refresh, after all bean definitions are loaded and before any ordinary singleton is created, Spring calls this method on every processor. The processor receives the bean factory and can read and change its bean definitions.

Analogy: If beans are dishes, bean definitions are the recipes. A BeanPostProcessor adds garnish to each dish after it is cooked. A BeanFactoryPostProcessor edits the recipe book before anyone starts cooking: it can change an ingredient, mark a dish "cook on order only", or add a new recipe.

2. Bean Definitions: What a BeanFactoryPostProcessor Changes

A bean definition (BeanDefinition) describes how to create a bean. Component scanning, @Bean methods and auto-configuration all produce bean definitions. Important properties include:

PropertyMeaningMethod
Bean class nameWhich class to instantiategetBeanClassName()
ScopeSingleton, prototype, request...setScope(...)
Lazy initCreate at startup or on first usesetLazyInit(...)
Primary and fallbackPreference when several beans matchsetPrimary(...), setFallback(...)
Init and destroy methodsLifecycle callbackssetInitMethodName(...)
Property values and constructor argumentsValues to injectgetPropertyValues()
Role and descriptionApplication or infrastructure bean, and a human-readable notesetRole(...), setDescription(...)
Where BeanFactoryPostProcessors act during the context refreshFirst, bean definitions are loaded from configuration classes, component scanning and auto-configuration. Next, BeanDefinitionRegistryPostProcessors may add or remove definitions, and BeanFactoryPostProcessors may modify them. Then bean post-processors are registered, and only after that are ordinary singleton beans instantiated, at which point BeanPostProcessors act on the bean instances. Load bean definitions (scan, @Bean, auto-config) Registry post-processors add or remove definitions BeanFactory- PostProcessors modify definitions Create beans BeanPostProcessors act on each instance no ordinary bean exists yet no ordinary bean exists yet instances exist
BeanFactoryPostProcessors edit the recipes; BeanPostProcessors act later, on the beans cooked from them.

3. BeanFactoryPostProcessor vs BeanPostProcessor

AspectBeanFactoryPostProcessorBeanPostProcessor
Works onBean definitions (recipes)Bean instances (objects)
RunsOnce per context, before beans are createdFor every bean, during its creation
Typical jobChange scope or lazy flag, resolve placeholders, register beansInject dependencies, call callbacks, wrap in proxies
Can create beans safely?No: creating one triggers early instantiationReceives beans as they are created
Spring examplesConfigurationClassPostProcessor, PropertySourcesPlaceholderConfigurerAutowiredAnnotationBeanPostProcessor, auto-proxy creators

The instance side is explained in BeanPostProcessor in Spring.

4. Built-In BeanFactoryPostProcessors

ProcessorWhat it does
ConfigurationClassPostProcessorParses @Configuration classes, runs component scanning, processes @Import and @Bean methods, and so loads auto-configuration. It is a registry post-processor and runs first.
PropertySourcesPlaceholderConfigurerResolves ${...} placeholders in bean definitions and enables them in @Value; Spring Boot registers one automatically
EventListenerMethodProcessorPrepares the detection of @EventListener methods
CustomScopeConfigurerRegisters custom scopes such as a thread scope; see bean scopes
LazyInitializationBeanFactoryPostProcessorSpring Boot's processor behind spring.main.lazy-initialization

5. Example 1: Modifying Existing Bean Definitions

A reporting module contains several expensive report generators that are rarely used. Instead of remembering @Lazy on each one, a processor marks every bean definition whose class carries a @HeavyReport annotation as lazy.

HeavyReport.java
package com.javabytechie.shop.report;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HeavyReport {
}
HeavyReportLazyPostProcessor.java
package com.javabytechie.shop.report;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class HeavyReportLazyPostProcessor implements BeanFactoryPostProcessor {

    private static final Logger log = LoggerFactory.getLogger(HeavyReportLazyPostProcessor.class);

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        for (String name : beanFactory.getBeanDefinitionNames()) {
            BeanDefinition definition = beanFactory.getBeanDefinition(name);
            if (definition instanceof AnnotatedBeanDefinition annotated
                    && annotated.getMetadata().hasAnnotation(HeavyReport.class.getName())) {
                definition.setLazyInit(true);
                log.info("Bean '{}' marked lazy", name);
            }
        }
    }
}
SalesReportGenerator.java
package com.javabytechie.shop.report;

import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
@HeavyReport
public class SalesReportGenerator {

    private static final Logger log = LoggerFactory.getLogger(SalesReportGenerator.class);

    @PostConstruct
    void loadTemplates() {
        log.info("SalesReportGenerator created");
    }
}
ReportConfig.java
package com.javabytechie.shop.report;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class ReportConfig {

    @Bean
    static HeavyReportLazyPostProcessor heavyReportLazyPostProcessor() {
        return new HeavyReportLazyPostProcessor();
    }
}
Console
Bean 'salesReportGenerator' marked lazy
Started ShopApplication in 1.02 seconds (process running for 1.27)

The processor reads the annotation from the definition's metadata, which scanning collected from the bytecode, so it never loads or instantiates the class. "SalesReportGenerator created" appears only when something first uses the bean. The method is static for reasons explained in section 9.

6. Example 2: Registering Beans with BeanDefinitionRegistryPostProcessor

BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor with postProcessBeanDefinitionRegistry(BeanDefinitionRegistry), which runs earlier and may add definitions. Here a shop registers one payment gateway bean for each provider listed in configuration:

application.properties
shop.payment.providers=card,upi,wallet
ConfiguredGateway.java
package com.javabytechie.shop.payment;

import java.math.BigDecimal;

public class ConfiguredGateway {

    private final String provider;

    public ConfiguredGateway(String provider) {
        this.provider = provider;
    }

    public String charge(String orderId, BigDecimal amount) {
        return provider.toUpperCase() + "-" + orderId + "-" + amount;
    }
}
PaymentGatewayRegistryPostProcessor.java
package com.javabytechie.shop.payment;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;

public class PaymentGatewayRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor, EnvironmentAware {

    private static final Logger log = LoggerFactory.getLogger(PaymentGatewayRegistryPostProcessor.class);
    private Environment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        List<String> providers = Binder.get(environment)
                .bind("shop.payment.providers", Bindable.listOf(String.class))
                .orElse(List.of());
        for (String provider : providers) {
            registry.registerBeanDefinition(provider + "Gateway",
                    BeanDefinitionBuilder.genericBeanDefinition(ConfiguredGateway.class)
                            .addConstructorArgValue(provider)
                            .getBeanDefinition());
            log.info("Registered bean '{}Gateway'", provider);
        }
    }
}
PaymentConfig.java
package com.javabytechie.shop.payment;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
class PaymentConfig {

    @Bean
    static PaymentGatewayRegistryPostProcessor paymentGatewayRegistryPostProcessor() {
        return new PaymentGatewayRegistryPostProcessor();
    }
}
Console
Registered bean 'cardGateway'
Registered bean 'upiGateway'
Registered bean 'walletGateway'

Any bean can now inject Map<String, ConfiguredGateway> and receive all three, as described in dependency injection in Spring. The postProcessBeanFactory method is inherited with an empty default, so it does not need to be implemented.

7. The Modern Alternative: BeanRegistrar in Spring Framework 7

Spring Framework 7 added BeanRegistrar, a dedicated API for registering beans programmatically. It receives a BeanRegistry and the Environment directly, needs no early-created processor bean, and works with ahead-of-time processing. The same payment example becomes:

PaymentGatewayRegistrar.java
package com.javabytechie.shop.payment;

import java.util.List;
import org.springframework.beans.factory.BeanRegistrar;
import org.springframework.beans.factory.BeanRegistry;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;

class PaymentGatewayRegistrar implements BeanRegistrar {

    @Override
    public void register(BeanRegistry registry, Environment env) {
        List<String> providers = Binder.get(env)
                .bind("shop.payment.providers", Bindable.listOf(String.class))
                .orElse(List.of());
        for (String provider : providers) {
            registry.registerBean(provider + "Gateway", ConfiguredGateway.class,
                    spec -> spec.supplier(context -> new ConfiguredGateway(provider)));
        }
    }
}
PaymentConfig.java (with BeanRegistrar)
@Configuration
@Import(PaymentGatewayRegistrar.class)
class PaymentConfig {
}
Version note: BeanRegistrar and BeanRegistry live in org.springframework.beans.factory and are available from Spring Framework 7.0, which means Spring Boot 4. On Spring Boot 3.x, use a BeanDefinitionRegistryPostProcessor as in section 6. For new code that registers beans, prefer BeanRegistrar; keep BeanFactoryPostProcessor for modifying existing definitions.

8. Order of Execution

  1. Registry post-processors registered programmatically on the context.
  2. Registry post-processor beans that implement PriorityOrdered (including ConfigurationClassPostProcessor, which loads most of your bean definitions), then Ordered, then the rest, repeated until no new registry processors appear.
  3. The postProcessBeanFactory method of all registry post-processors.
  4. Plain BeanFactoryPostProcessor beans: PriorityOrdered, then Ordered, then the rest.

Because configuration classes are parsed in step 2, your processor declared in a @Configuration class is discovered there and then run in a later round.

9. Rules and Pitfalls

  • Declare the @Bean method static. Otherwise Spring must create the configuration class instance early to call it; Spring logs a warning that @Autowired and @Value in that configuration class will not work.
  • Never call getBean() inside a processor. It instantiates a bean before bean post-processors are registered, so that bean misses injection of annotated fields, proxies and other processing.
  • Do not use @Autowired or @Value in the processor. The processors that handle them are not active yet; implement EnvironmentAware or read definitions from the factory instead.
  • Remember that definitions may not have a class name, for example beans created by factory methods; check for null.
  • Keep the work small. The processor runs on the startup path, once per context.

10. Best Practices

  • Use a BeanFactoryPostProcessor to modify definitions, such as lazy flags, scopes or roles.
  • Use BeanRegistrar to add beans on Spring Framework 7 and later.
  • Read annotations from the definition's metadata instead of loading classes.
  • Get configuration through EnvironmentAware and Binder, not through injection.
  • Prefer standard features first: @Lazy, @Scope, conditions and profiles cover most needs without a processor.

11. Summary

A BeanFactoryPostProcessor in Spring runs once during the context refresh, after bean definitions are loaded and before ordinary beans are created, and can read and change those definitions. Its sub-interface BeanDefinitionRegistryPostProcessor runs earlier and can add definitions, which is how Spring processes @Configuration classes; Spring Framework 7's BeanRegistrar is now the simpler way to register beans in code. Declare processors in static @Bean methods, never create beans inside them, and use them only when annotations, conditions and properties cannot express what you need.

12. References