java / expert
Snippet
Advanced Bean Metadata Manipulation via BeanFactoryPostProcessor
The BeanFactoryPostProcessor allows you to intercept and modify bean definitions before the objects are even instantiated, enabling cross-cutting changes like scope overrides or dynamic property injection.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
@Componentpublic class AuditMetadataProcessor implements BeanFactoryPostProcessor {@Overridepublic void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {for (String beanName : beanFactory.getBeanDefinitionNames()) {BeanDefinition bd = beanFactory.getBeanDefinition(beanName);if (bd.getBeanClassName() != null && bd.getBeanClassName().contains("Service")) {bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);}}}}
spring
Breakdown
1
implements BeanFactoryPostProcessor
Interface for modifying the application context's internal bean definitions.
2
postProcessBeanFactory(...)
Callback that runs after all bean definitions are loaded but before instantiation.
3
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE)
Dynamically changing the lifecycle scope of specific beans at runtime.