java / expert
Snippet
Custom Annotation Processing with BeanPostProcessor
BeanPostProcessors allow for custom modification of new bean instances. This expert-level pattern is used to wrap beans in proxies, inject additional behavior, or perform validation after the Spring container has fully initialized the bean properties but before it is used by the application.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Componentpublic class LoggingBeanPostProcessor implements BeanPostProcessor {@Overridepublic Object postProcessAfterInitialization(Object bean, String beanName) {if (bean.getClass().isAnnotationPresent(LogExecution.class)) {return Proxy.newProxyInstance(bean.getClass().getClassLoader(),bean.getClass().getInterfaces(),(proxy, method, args) -> {System.out.println("Executing: " + method.getName());return method.invoke(bean, args);});}return bean;}}
spring
Breakdown
1
public Object postProcessAfterInitialization(Object bean, String beanName)
Hook called by Spring after a bean is fully initialized and its dependencies are injected.
2
return Proxy.newProxyInstance(...)
Wraps the original bean in a dynamic proxy to intercept method calls for cross-cutting concerns.