BeanFactoryPostProcessor in Spring
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:
@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.
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:
| Property | Meaning | Method |
|---|---|---|
| Bean class name | Which class to instantiate | getBeanClassName() |
| Scope | Singleton, prototype, request... | setScope(...) |
| Lazy init | Create at startup or on first use | setLazyInit(...) |
| Primary and fallback | Preference when several beans match | setPrimary(...), setFallback(...) |
| Init and destroy methods | Lifecycle callbacks | setInitMethodName(...) |
| Property values and constructor arguments | Values to inject | getPropertyValues() |
| Role and description | Application or infrastructure bean, and a human-readable note | setRole(...), setDescription(...) |
3. BeanFactoryPostProcessor vs BeanPostProcessor
| Aspect | BeanFactoryPostProcessor | BeanPostProcessor |
|---|---|---|
| Works on | Bean definitions (recipes) | Bean instances (objects) |
| Runs | Once per context, before beans are created | For every bean, during its creation |
| Typical job | Change scope or lazy flag, resolve placeholders, register beans | Inject dependencies, call callbacks, wrap in proxies |
| Can create beans safely? | No: creating one triggers early instantiation | Receives beans as they are created |
| Spring examples | ConfigurationClassPostProcessor, PropertySourcesPlaceholderConfigurer | AutowiredAnnotationBeanPostProcessor, auto-proxy creators |
The instance side is explained in BeanPostProcessor in Spring.
4. Built-In BeanFactoryPostProcessors
| Processor | What it does |
|---|---|
ConfigurationClassPostProcessor | Parses @Configuration classes, runs component scanning, processes @Import and @Bean methods, and so loads auto-configuration. It is a registry post-processor and runs first. |
PropertySourcesPlaceholderConfigurer | Resolves ${...} placeholders in bean definitions and enables them in @Value; Spring Boot registers one automatically |
EventListenerMethodProcessor | Prepares the detection of @EventListener methods |
CustomScopeConfigurer | Registers custom scopes such as a thread scope; see bean scopes |
LazyInitializationBeanFactoryPostProcessor | Spring 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.
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 {
}
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);
}
}
}
}
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");
}
}
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();
}
}
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:
shop.payment.providers=card,upi,wallet
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;
}
}
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);
}
}
}
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();
}
}
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:
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)));
}
}
}
@Configuration
@Import(PaymentGatewayRegistrar.class)
class PaymentConfig {
}
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
- Registry post-processors registered programmatically on the context.
- Registry post-processor beans that implement
PriorityOrdered(includingConfigurationClassPostProcessor, which loads most of your bean definitions), thenOrdered, then the rest, repeated until no new registry processors appear. - The
postProcessBeanFactorymethod of all registry post-processors. - Plain
BeanFactoryPostProcessorbeans:PriorityOrdered, thenOrdered, 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
@Beanmethodstatic. Otherwise Spring must create the configuration class instance early to call it; Spring logs a warning that@Autowiredand@Valuein 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
@Autowiredor@Valuein the processor. The processors that handle them are not active yet; implementEnvironmentAwareor 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
BeanFactoryPostProcessorto modify definitions, such as lazy flags, scopes or roles. - Use
BeanRegistrarto add beans on Spring Framework 7 and later. - Read annotations from the definition's metadata instead of loading classes.
- Get configuration through
EnvironmentAwareandBinder, 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
BeanFactoryPostProcessor in Spring Interview Questions and Answers
Common interview questions on BeanFactoryPostProcessor in Spring, from basic to scenario-based, with short answers you can explain in your own words.
Q. What is the difference between a BeanFactoryPostProcessor and a BeanPostProcessor?
Answer: A BeanFactoryPostProcessor runs once, before any ordinary bean exists, and works on bean definitions: it can change scopes, lazy flags or property values. A BeanPostProcessor runs for every bean while it is being created and works on the instance: it can inject, initialize or wrap it in a proxy. One edits the recipes, the other processes each dish.
Q. Why is calling getBean() inside a BeanFactoryPostProcessor dangerous?
Answer: It forces the bean, and all its dependencies, to be created before bean post-processors are registered. Those beans miss annotation-driven injection, lifecycle callbacks handled by processors, and proxies for transactions or async execution, which leads to subtle bugs. A processor should only read and modify bean definitions.
Q. What is a BeanDefinitionRegistryPostProcessor, and when does it run?
Answer: It extends BeanFactoryPostProcessor with postProcessBeanDefinitionRegistry, which can add or remove bean definitions. All registry post-processors run before plain bean factory post-processors, ordered by PriorityOrdered, Ordered and the rest. ConfigurationClassPostProcessor is the most important one: it parses configuration classes and runs component scanning.
Q. Which component resolves ${...} placeholders in @Value annotations?
Answer: A PropertySourcesPlaceholderConfigurer, which is a bean factory post-processor. It resolves placeholders in bean definitions against the Environment and registers an embedded value resolver used for @Value. Spring Boot registers one automatically; in plain Spring you declare it in a static @Bean method.
Q. What is BeanRegistrar in Spring Framework 7, and when would you use it?
Answer: It is an interface for registering beans programmatically, imported with @Import on a configuration class. Its register(BeanRegistry, Environment) method can use loops, conditions and the environment to register beans with suppliers and options such as lazy, prototype or primary. Use it instead of a BeanDefinitionRegistryPostProcessor when you need a variable number of beans, for example one per configured tenant or provider.
Q. A custom BeanFactoryPostProcessor has an @Value field that is always null. Why?
Answer: Bean factory post-processors are instantiated before bean post-processors are registered, so AutowiredAnnotationBeanPostProcessor, which handles @Value and @Autowired, never processes them. Implement EnvironmentAware and read the value from the Environment, or use Binder for structured values. The same applies to fields of a non-static configuration class that declares such a processor.