开发者

Obtain real Class object for Spring bean

开发者 https://www.devze.com 2022-12-20 18:50 出处:网络
I am using Spring to inject beans. And I am using some annotations to annotate bean methods (Security, TransactionManagement, ExceptionHanling, Logging). The problem is:

I am using Spring to inject beans. And I am using some annotations to annotate bean methods (Security, TransactionManagement, ExceptionHanling, Logging). The problem is:

I want to create JUnit test to check if I forgot annotate some methods. But Spr开发者_JAVA技巧ing returns $ProxyXXX class without any annotations on methods..

Method[] methods = logic.getClass().getMethods();

  for (Method method : methods) {
     Annotation[] annotations = method.getAnnotations();   // empty array!

How can I get annotations for method or obtain a real class object?

P.S. Spring 2.5.6, JDKDynamicProxy (not CGLib)


Spring's interface-based proxies implement TargetClassAware.


Or you can just call: AopUtils.getTargetClass(java.lang.Object) It is a static method call.


You can cast the proxied object to get the object and class it acts as a proxy for (see TargetSource):

Advised advised = (Advised) proxy;
Class<?> cls = advised.getTargetSource().getTargetClass();

Generally you should follow the Spring principles and keep obtaining the correct class as unobtrusive as possible. Meaning that as little classes as possible should depend on the Spring Framework APIs (maybe add a ClassLocator and a SpringProxyClassLocator implementation).


AopUtils.getTargetClass only unwraps one level. Use AopProxyUtils.ultimateTargetClass(instance) instead.

(I'm aware this is an 11 years old question, but it's still coming up high in Google, so it benefits from a new answer)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号