Spring proxy获取target总结
Aspect方式
在使用Aspect方式时候,在around advice的第一个参数ProceedingJoinPoint(Join Point)的实现类,可以通过getTarget的方式获取被代理的plain service.
Advisor方式
使用MethodInterceptor作为advice,参数类型是MethodInvocation. 这时候就可以强转成Advised类,使用getTargetSource
方法获取到具体的plain service.
advised
类描述:
Interface to be implemented by classes that hold the configuration
of a factory of AOP proxies. This configuration includes the
Interceptors and other advice, Advisors, and the proxied interfaces.Any AOP proxy obtained from Spring can be cast to this interface to
allow manipulation of its AOP advice.
示例代码:
public class ProxyUtils {
public static <T> T getProxyTarget(Object proxy) {
if (!AopUtils.isAopProxy(proxy)) {
throw new IllegalStateException("Target must be a proxy");
}
TargetSource targetSource = ((Advised) proxy).getTargetSource();
return getTarget(targetSource);
}
private static <T> T getTarget(TargetSource targetSource) {
try {
return (T) targetSource.getTarget();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}