Java Spring Quick Tip — Episode 2

Daniel Zielinski
2 min readMar 19, 2023

Overriding existing beans in Spring Boot

@Slf4j
@Configuration
class JdbcConfig implements BeanPostProcessor {

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (bean instanceof DataSource) {
log.info("Decorating data source with P6DataSource");
return new P6DataSource((DataSource) bean);
}
return bean;
}
}

In Spring Framework, a BeanPostProcessor is a special type of bean that allows you to customize the instantiation and initialization of other beans in the container.

A BeanPostProcessor defines two methods: postProcessBeforeInitialization() and postProcessAfterInitialization(). These methods are invoked by Spring for every bean in the container, giving you the opportunity to perform custom initialization and configuration tasks on those beans.

  1. postProcessBeforeInitialization(): This method is called after the bean has been instantiated, but before any initialization callbacks have been invoked. You can use this method to modify the bean instance before it is initialized.
  2. postProcessAfterInitialization(): This method is called after all initialization callbacks have been invoked on the bean. You can use this method to perform additional configuration or…

--

--