Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring proxy doesn't contain the annotation of the proxied class

I have an interface annotated with @Transactional. Then concrete classes implementing that interface. Because of the annotation spring creates a proxy for every class implementing the interface.

My problem is that at container boot-up time I am checking if some of the classes are annotated with a specific user custom type annotation (if not I am throwing an exception). It seems that getAnnotation() method on the proxy returns null.

Is the proxy not supposed to contain all the attributes(e.g annotations) associated with the proxied class?

like image 273
Todor Kolev Avatar asked Sep 11 '25 18:09

Todor Kolev


1 Answers

Spring creates proxies and by default JDK Dynamic Proxies, it basically creates a dynamic class a boottime (those nice $Proxy42 classes) which act like instances of your interfaces. If you now call get class you will get that dynamically created classes.

Use the AopProxyUtils utility class from spring to get the actual Class which contains the annotations.

So instead of

Class<?> clazz = someObject.getClass();

do

Class<?> clazz = AopProxyUtils.ultimateTargetClass(someObject);

That should give you the actual (wrapped) class.

like image 161
M. Deinum Avatar answered Sep 14 '25 10:09

M. Deinum