Bean lifecycle and scopes · Topic 5 of 5
BeanPostProcessor
Definition​
A BeanPostProcessor is a hook that Spring calls for every bean right after it is created. It can inspect or even replace the bean. This is how Spring itself adds features such as @Transactional and @Async (by wrapping beans in proxies).
Example code​
A hook that sees every bean as it is created
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
class Greeter { }
class Mailer { }
class LoggingPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof Greeter || bean instanceof Mailer) {
System.out.println("created bean: " + beanName); // inspect (or wrap) every bean
}
return bean; // return the bean, or a proxy around it
}
}
@Configuration
class AppConfig {
@Bean static LoggingPostProcessor logger() { return new LoggingPostProcessor(); } // static: it is needed early
@Bean Greeter greeter() { return new Greeter(); }
@Bean Mailer mailer() { return new Mailer(); }
}
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("ready");
}
}
}
// Output:
// created bean: greeter
// created bean: mailer
// ready
Finished this page? Track your progress (saved only in your browser).