Quick revision
The short answer
We implement postProcessAfterInitialization, find the bean's real class (looking through any existing proxy) and check it for @Timed. If it is present, we build a proxy with Spring's ProxyFactory, add a MethodInterceptor that measures the time around invocation.proceed() and logs it, and return the proxy so it replaces the bean. The post-processor is registered with a static @Bean method and does not inject other beans; in practice an @Aspect or Micrometer's @Timed support does the same job with less code.
What to remember
In this answer, we wrote a BeanPostProcessor that wraps @Timed beans. In postProcessAfterInitialization it finds the real class with AopUtils.getTargetClass, checks for the annotation, builds a CGLIB proxy with ProxyFactory and a MethodInterceptor that times invocation.proceed() in a finally block, and returns the proxy to replace the bean. We registered it with a static @Bean method and no dependencies, tested it, went through pitfalls such as self-calls, final classes and double proxies, and saw that an @Aspect or Micrometer's @Timed with TimedAspect does the same job with less code.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We implement postProcessAfterInitialization, find the bean's real class (looking through any existing proxy) and check it for @Timed. If it is present, we build a proxy with Spring's ProxyFactory, add a MethodInterceptor that measures the time around invocation.proceed() and logs it, and return the proxy so it replaces the bean. The post-processor is registered with a static @Bean method and does not inject other beans; in practice an @Aspect or Micrometer's @Timed support does the same job with less code.
Why this question is asked
Writing a BeanPostProcessor by hand is a classic coding exercise because it touches several things at once: the bean lifecycle, how Spring builds proxies, and the subtle rules about how post-processors themselves are created. Interviewers want working code, and they also want us to say what can go wrong and what we would use in real projects. In this answer, we will define the annotation, write the post-processor step by step, register it correctly, test it, look at the pitfalls such as proxy types and existing proxies, and finally compare it with an aspect and with Micrometer.
1The Annotation and the Plan
First we need the annotation. It must be kept at runtime, because our post-processor reads it while the application runs, and it targets classes, because the question asks for beans annotated with it.
The plan follows the bean lifecycle. Spring calls every BeanPostProcessor twice for each bean, before and after its initialisation callbacks. We use the 'after' call, postProcessAfterInitialization, because by then the bean is fully initialised, @PostConstruct has run, and other post-processors have had their turn earlier in the chain. Whatever we return from that method becomes the bean, so returning a proxy replaces it.
2Writing the Post-Processor
Here is the complete post-processor. It uses ProxyFactory, Spring's programmatic API for building AOP proxies, and a MethodInterceptor, the AOP Alliance interface for code that runs around a method call.
7 messages in order. Play them, or step through them one at a time.
Let us go through the reasons. AopUtils.getTargetClass looks through an existing Spring proxy to the class underneath; without it, a bean already proxied for @Transactional would show a generated class and the annotation check could fail. AnnotatedElementUtils.hasAnnotation also finds @Timed when it is used as a meta-annotation on another annotation, so teams can build their own composed annotations.
setProxyTargetClass(true) asks for a CGLIB subclass instead of a JDK proxy. A JDK proxy only implements interfaces, so any bean that injects QuoteService by its class would fail with a type mismatch. The subclass is an instance of QuoteService, so injection by class keeps working. The interceptor uses try and finally so the time is logged even when the method throws, and the exception still reaches the caller unchanged.
3Registering It Correctly
Post-processors are created early, before ordinary beans, because Spring needs them in place to process those beans. So the way we register ours matters.
The method is static so Spring can call it without creating the TimingConfig instance. If it were an instance method, Spring would have to create TimingConfig early, together with anything TimingConfig injects, and those beans would be created before the other post-processors are registered. They would then miss processing, and Spring would log that they are not eligible for getting processed by all BeanPostProcessors. For the same reason, the post-processor itself takes no dependencies; it only uses a logger. If it needed a MeterRegistry, for example, it should look it up lazily through an ObjectProvider rather than inject it directly.
4Testing It
A short Spring test proves both the timing and that the bean is still usable by its class.
5Pitfalls Worth Mentioning
Self-calls are not timed. If price() calls another method of QuoteService, that call goes to this and never passes through the proxy, exactly as with @Transactional. Final classes and final methods cannot be handled by a CGLIB subclass: a final class makes proxy creation fail, and a final method silently runs without timing.
Order matters when several proxies are involved. Our post-processor wraps whatever it receives, so a bean that was already proxied for transactions gets a second proxy around the first, and the timing then includes the transaction. If that matters, we can implement Ordered to control where we run, or add our interceptor to the existing proxy when the bean is an instance of Advised. Finally, the cost is small but not zero: an extra call layer and a log line per invocation, so logging at info level on a hot path should become a metric instead.
6What I Would Use in Practice
For real projects I would rarely write this post-processor. An @Aspect does the same with less code, because Spring's auto-proxy creator already handles finding beans, building proxies and ordering them.
And if the goal is metrics rather than log lines, Micrometer already provides io.micrometer.core.annotation.Timed together with a TimedAspect bean, which records a Timer per method and publishes it to whatever monitoring system the application uses. Spring's @Observed and observation support go further and add tracing. The hand-written post-processor is still worth knowing, because it shows what all of these do underneath.
7Follow-up questions
Why postProcessAfterInitialization and not postProcessBeforeInitialization?
If we returned the proxy from the 'before' method, the init callbacks such as afterPropertiesSet() would be called on the proxy, and other post-processors would see a proxy where they expect the real bean. Wrapping after initialisation keeps all of that on the real object and only changes what callers receive.
What changes if the bean implements an interface and we do not set proxyTargetClass?
ProxyFactory then creates a JDK dynamic proxy implementing the bean's interfaces. Beans that inject the interface keep working, but anything that injects the concrete class fails at startup because the proxy is not an instance of that class.
How would you support @Timed on individual methods?
We would check whether the class or any of its methods carries the annotation, and in the interceptor time only the methods annotated, using AnnotatedElementUtils on invocation.getMethod(), or simply use an aspect with an @annotation pointcut.
8Conclusion
In this answer, we wrote a BeanPostProcessor that wraps @Timed beans. In postProcessAfterInitialization it finds the real class with AopUtils.getTargetClass, checks for the annotation, builds a CGLIB proxy with ProxyFactory and a MethodInterceptor that times invocation.proceed() in a finally block, and returns the proxy to replace the bean. We registered it with a static @Bean method and no dependencies, tested it, went through pitfalls such as self-calls, final classes and double proxies, and saw that an @Aspect or Micrometer's @Timed with TimedAspect does the same job with less code.
Open with
I would implement BeanPostProcessor and use postProcessAfterInitialization, because by then the bean is fully initialised and whatever I return replaces it. First I get the real class with AopUtils.getTargetClass, so a bean that is already a transactional proxy is still recognised, and check it for @Timed with AnnotatedElementUtils.
Then, if they want more
If it is not annotated, I return the bean unchanged.
If it is, I create a ProxyFactory around the bean, set proxyTargetClass to true so it is a CGLIB subclass and injection by concrete class keeps working, and add a MethodInterceptor that records nanoTime, calls invocation.proceed in a try block and logs the elapsed time in finally, so the exception still propagates. Then I return factory.getProxy.
I register it with a static @Bean method, so Spring does not have to create the configuration class early, and I do not inject other beans into it, because post-processors are created before regular beans and anything they inject would miss post-processing.
I would mention the limits: self-calls are not timed, final classes or methods cannot be proxied, and it stacks on existing proxies. In a real project I would rather use an @Aspect with an @within pointcut, or Micrometer's @Timed with TimedAspect, which give me metrics instead of log lines.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Framework reference, Core technologies
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a BeanPostProcessor that wraps every bean annotated with a custom @Timed...": https://scrivio-interview-library.netlify.app/spring-boot/bean-lifecycle/7bb436b9af/