相关阅读
简介
已配置的AOP代理的委托接口,支持创建实际的代理对象;
可以使用DefaultAopProxyFactory
提供的开箱即用的JDK动态代理和CGLIB代理;
源码
public interface AopProxy {
// 使用默认类加载器(通常是线程上下文类加载器)创建代理对象
Object getProxy();
// 使用指定的类加载器创建代理对象
Object getProxy(@Nullable ClassLoader classLoader);
}
实现子类
public interface AopProxy
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable
class CglibAopProxy implements AopProxy, Serializable
class ObjenesisCglibAopProxy extends CglibAopProxy
JdkDynamicAopProxy
简介
基于JDK动态代理Proxy
实现的AopProxy
,用于Spring AOP框架;
创建的动态代理对象实现了AopProxy
暴露的接口,可以用于代理接口的方法,而不能代理类的方法;
如果目标对象类型是线程安全的,则代理也是线程安全的;
如果所有的Advisor
和TargetSource
都支持序列化,则代理也支持序列化;
核心代码
final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializable {
// 代理的配置信息
private final AdvisedSupport advised;
// 代理的接口集合
private final Class<?>[] proxiedInterfaces;
// 代理的接口是否定义equals方法
private boolean equalsDefined;
// 代理的接口是否定义hashCode方法
private boolean hashCodeDefined;
public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
// 校验AdvisedSupport
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
// 如果Advisor和`TargetSource`都不存在,则无法创建代理
throw new AopConfigException("No advisors and no TargetSource specified");
}
this.advised = config;
// 获取代理的接口集合
this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
// 查找代理的接口是否实现了equals和hashCode方法
findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
}
@Override
public Object getProxy() {
// 使用默认地类加载器,通常是线程上下文类加载器
return getProxy(ClassUtils.getDefaultClassLoader());
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
}
// 通过Proxy创建代理,将自身作为InvocationHandler传入
return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
}
private void findDefinedEqualsAndHashCodeMethods(Class<?>[] proxiedInterfaces) {
// 遍历代理的接口集合
for (Class<?> proxiedInterface : proxiedInterfaces) {
Method[] methods = proxiedInterface.getDeclaredMethods();
for (Method method : methods) {
if (AopUtils.isEqualsMethod(method)) {
// 存在equals方法
this.equalsDefined = true;
}
if (AopUtils.isHashCodeMethod(method)) {
// 存在hashCode方法
this.hashCodeDefined = true;
}
if (this.equalsDefined && this.hashCodeDefined) {
// 已经找到equals和hashCode方法,则无需继续查找
return;
}
}
}
}
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
TargetSource targetSource = this.advised.targetSource;
Object target = null;
try {
if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
// 没有实现equals方法
return equals(args[0]);
}
else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
// 没有实现hashCode方法
return hashCode();
}
else if (method.getDeclaringClass() == DecoratingProxy.class) {
// DecoratingProxy只定义了getDecoratedClass方法
return AopProxyUtils.ultimateTargetClass(this.advised);
}
else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
// Service invocations on ProxyConfig with the proxy config...
// 代理可以转换为Advised,通过反射执行方法
return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
}
Object retVal;
if (this.advised.exposeProxy) {
// 暴露当前代理
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 获取拦截器链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
// Check whether we have any advice. If we don't, we can fallback on direct
// reflective invocation of the target, and avoid creating a MethodInvocation.
if (chain.isEmpty()) {
// 没有配置拦截器,则通过反射,直接使用目标对象执行方法
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
else {
// We need to create a method invocation...
// 使用配置的拦截器链创建MethodInvocation
MethodInvocation invocation =
new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
// MethodInvocation执行时,会先执行完拦截器的逻辑,最后才使用目标对象执行方法
retVal = invocation.proceed();
}
// 处理方法的返回值
Class<?> returnType = method.getReturnType();
if (retVal != null && retVal == target &&
returnType != Object.class && returnType.isInstance(proxy) &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// 如果方法返回值为自身,则修正为代理
// 但无法做到当返回值持有自身的一个引用时,将引用修正为代理
retVal = proxy;
}
else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
// 返回值类型为基础类型时,却无返回值的异常处理
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// 释放目标对象
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// 恢复当前上下文的代理
AopContext.setCurrentProxy(oldProxy);
}
}
}
@Override
public boolean equals(@Nullable Object other) {
if (other == this) {
return true;
}
if (other == null) {
return false;
}
JdkDynamicAopProxy otherProxy;
if (other instanceof JdkDynamicAopProxy) {
otherProxy = (JdkDynamicAopProxy) other;
}
else if (Proxy.isProxyClass(other.getClass())) {
// 获取InvocationHandler
InvocationHandler ih = Proxy.getInvocationHandler(other);
if (!(ih instanceof JdkDynamicAopProxy)) {
return false;
}
otherProxy = (JdkDynamicAopProxy) ih;
}
else {
// 其它类型无可比性
return false;
}
// AopProxy之间的比较
return AopProxyUtils.equalsInProxy(this.advised, otherProxy.advised);
}
@Override
public int hashCode() {
return JdkDynamicAopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode();
}
}
CglibAopProxy
简介
基于CGLIB代理实现的AopProxy
,用于Spring AOP框架;
如果目标对象是线程安全的,则代理也是线程安全的;
核心代码
class CglibAopProxy implements AopProxy, Serializable {
// 记录校验过final方法的类型
private static final Map<Class<?>, Boolean> validatedClasses = new WeakHashMap<>();
// 代理的配置信息
protected final AdvisedSupport advised;
// 构造参数
@Nullable
protected Object[] constructorArgs;
// 构造参数类型
@Nullable
protected Class<?>[] constructorArgTypes;
public CglibAopProxy(AdvisedSupport config) throws AopConfigException {
// 校验AdvisedSupport
Assert.notNull(config, "AdvisedSupport must not be null");
if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
throw new AopConfigException("No advisors and no TargetSource specified");
}
this.advised = config;
this.advisedDispatcher = new AdvisedDispatcher(this.advised);
}
public void setConstructorArguments(@Nullable Object[] constructorArgs, @Nullable Class<?>[] constructorArgTypes) {
if (constructorArgs == null || constructorArgTypes == null) {
throw new IllegalArgumentException("Both 'constructorArgs' and 'constructorArgTypes' need to be specified");
}
if (constructorArgs.length != constructorArgTypes.length) {
throw new IllegalArgumentException("Number of 'constructorArgs' (" + constructorArgs.length +
") must match number of 'constructorArgTypes' (" + constructorArgTypes.length + ")");
}
// 设置创建代理时需要的构造参数
this.constructorArgs = constructorArgs;
this.constructorArgTypes = constructorArgTypes;
}
@Override
public Object getProxy() {
// 默认无类加载器
return getProxy(null);
}
@Override
public Object getProxy(@Nullable ClassLoader classLoader) {
if (logger.isTraceEnabled()) {
logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
}
try {
// 目标对象类型必须有效,CGLIB是基于类进行代理
Class<?> rootClass = this.advised.getTargetClass();
Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
Class<?> proxySuperClass = rootClass;
if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {
// 目标对象类型是CGLIB创建的类型
proxySuperClass = rootClass.getSuperclass();
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
// 校验目标类型的final方法
validateClassIfNecessary(proxySuperClass, classLoader);
Enhancer enhancer = createEnhancer();
if (classLoader != null) {
enhancer.setClassLoader(classLoader);
if (classLoader instanceof SmartClassLoader &&
((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
enhancer.setUseCache(false);
}
}
// 设置继承的类
enhancer.setSuperclass(proxySuperClass);
// 设置需要实现的接口
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
// 获取方法回调
Callback[] callbacks = getCallbacks(rootClass);
Class<?>[] types = new Class<?>[callbacks.length];
for (int x = 0; x < types.length; x++) {
types[x] = callbacks[x].getClass();
}
// ProxyCallbackFilter决定method通过哪一个Callback回调
enhancer.setCallbackFilter(new ProxyCallbackFilter(
this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);
// 根据方法回调创建代理类并创建代理类的实例
return createProxyClassAndInstance(enhancer, callbacks);
}
catch (CodeGenerationException | IllegalArgumentException ex) {
throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
": Common causes of this problem include using a final class or a non-visible class",
ex);
}
catch (Throwable ex) {
// TargetSource.getTarget() failed
throw new AopConfigException("Unexpected AOP exception", ex);
}
}
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
enhancer.setInterceptDuringConstruction(false);
enhancer.setCallbacks(callbacks);
// 有构造参数则使用
return (this.constructorArgs != null && this.constructorArgTypes != null ?
enhancer.create(this.constructorArgTypes, this.constructorArgs) :
enhancer.create());
}
private Callback[] getCallbacks(Class<?> rootClass) throws Exception {
// Parameters used for optimization choices...
boolean exposeProxy = this.advised.isExposeProxy();
boolean isFrozen = this.advised.isFrozen();
boolean isStatic = this.advised.getTargetSource().isStatic();
// 用于处理有Advice chain的方法的调用
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
// 用于处理没有Advice chain且可以返回this的方法的调用
Callback targetInterceptor;
if (exposeProxy) {
targetInterceptor = (isStatic ?
new StaticUnadvisedExposedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedExposedInterceptor(this.advised.getTargetSource()));
}
else {
targetInterceptor = (isStatic ?
new StaticUnadvisedInterceptor(this.advised.getTargetSource().getTarget()) :
new DynamicUnadvisedInterceptor(this.advised.getTargetSource()));
}
// 用于处理没有Advice chain且不可以返回this的方法的调用
Callback targetDispatcher = (isStatic ?
new StaticDispatcher(this.advised.getTargetSource().getTarget()) : new SerializableNoOp());
Callback[] mainCallbacks = new Callback[] {
aopInterceptor, // for normal advice
targetInterceptor, // invoke target without considering advice, if optimized
new SerializableNoOp(), // no override for methods mapped to this
targetDispatcher, this.advisedDispatcher,
// 处理equals方法调用
new EqualsInterceptor(this.advised),
// 处理hashCode方法调用
new HashCodeInterceptor(this.advised)
};
Callback[] callbacks;
// 如果目标对象是静态的,且Advice chain不支持变动,则可以对方法调用做出优化
if (isStatic && isFrozen) {
Method[] methods = rootClass.getMethods();
Callback[] fixedCallbacks = new Callback[methods.length];
this.fixedInterceptorMap = CollectionUtils.newHashMap(methods.length);
// 使用FixedChainStaticTargetInterceptor处理方法的调用
for (int x = 0; x < methods.length; x++) {
Method method = methods[x];
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, rootClass);
fixedCallbacks[x] = new FixedChainStaticTargetInterceptor(
chain, this.advised.getTargetSource().getTarget(), this.advised.getTargetClass());
this.fixedInterceptorMap.put(method, x);
}
callbacks = new Callback[mainCallbacks.length + fixedCallbacks.length];
System.arraycopy(mainCallbacks, 0, callbacks, 0, mainCallbacks.length);
System.arraycopy(fixedCallbacks, 0, callbacks, mainCallbacks.length, fixedCallbacks.length);
// 记录FixedChainStaticTargetInterceptor起始位置
this.fixedInterceptorOffset = mainCallbacks.length;
}
else {
callbacks = mainCallbacks;
}
return callbacks;
}
@Nullable
private static Object processReturnType(
Object proxy, @Nullable Object target, Method method, @Nullable Object returnValue) {
if (returnValue != null && returnValue == target &&
!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
// 如果方法返回值为自身,则修正为代理
// 但无法做到当返回值持有自身的一个引用时,将引用修正为代理
returnValue = proxy;
}
Class<?> returnType = method.getReturnType();
if (returnValue == null && returnType != Void.TYPE && returnType.isPrimitive()) {
// 返回值类型为基础类型时,却无返回值的异常处理
throw new AopInvocationException(
"Null return value from advice does not match primitive return type for: " + method);
}
return returnValue;
}
// 处理目标对象是静态的且无Advice chain的方法的MethodInterceptor
private static class StaticUnadvisedInterceptor implements MethodInterceptor, Serializable {
@Nullable
private final Object target;
public StaticUnadvisedInterceptor(@Nullable Object target) {
this.target = target;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// 直接使用目标对象进行方法调用
Object retVal = methodProxy.invoke(this.target, args);
// 处理方法返回值
return processReturnType(proxy, this.target, method, retVal);
}
}
// 处理目标对象是静态的且无Advice chain的方法的MethodInterceptor,需要暴露代理对象
private static class StaticUnadvisedExposedInterceptor implements MethodInterceptor, Serializable {
@Nullable
private final Object target;
public StaticUnadvisedExposedInterceptor(@Nullable Object target) {
this.target = target;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
try {
// 暴露代理
oldProxy = AopContext.setCurrentProxy(proxy);
// 直接使用目标对象进行方法调用
Object retVal = methodProxy.invoke(this.target, args);
// 处理方法返回值
return processReturnType(proxy, this.target, method, retVal);
}
finally {
// 恢复当前上下文的代理
AopContext.setCurrentProxy(oldProxy);
}
}
}
// 处理目标对象是动态的且无Advice chain的方法的MethodInterceptor
private static class DynamicUnadvisedInterceptor implements MethodInterceptor, Serializable {
private final TargetSource targetSource;
public DynamicUnadvisedInterceptor(TargetSource targetSource) {
this.targetSource = targetSource;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// 获取目标对象
Object target = this.targetSource.getTarget();
try {
// 直接使用目标对象进行方法调用
Object retVal = methodProxy.invoke(target, args);
// 处理方法返回值
return processReturnType(proxy, target, method, retVal);
}
finally {
if (target != null) {
// 释放目标对象
this.targetSource.releaseTarget(target);
}
}
}
}
// 处理目标对象是动态的且无Advice chain的方法的MethodInterceptor,需要暴露代理对象
private static class DynamicUnadvisedExposedInterceptor implements MethodInterceptor, Serializable {
private final TargetSource targetSource;
public DynamicUnadvisedExposedInterceptor(TargetSource targetSource) {
this.targetSource = targetSource;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
// 获取目标对象
Object target = this.targetSource.getTarget();
try {
// 暴露代理
oldProxy = AopContext.setCurrentProxy(proxy);
// 直接使用目标对象进行方法调用
Object retVal = methodProxy.invoke(target, args);
// 处理方法返回值
return processReturnType(proxy, target, method, retVal);
}
finally {
// 恢复当前上下文的代理
AopContext.setCurrentProxy(oldProxy);
if (target != null) {
// 释放目标对象
this.targetSource.releaseTarget(target);
}
}
}
}
// 处理equals方法的MethodInterceptor
private static class EqualsInterceptor implements MethodInterceptor, Serializable {
private final AdvisedSupport advised;
public EqualsInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
// equals方法逻辑
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
Object other = args[0];
if (proxy == other) {
return true;
}
if (other instanceof Factory) {
Callback callback = ((Factory) other).getCallback(INVOKE_EQUALS);
if (!(callback instanceof EqualsInterceptor)) {
return false;
}
AdvisedSupport otherAdvised = ((EqualsInterceptor) callback).advised;
return AopProxyUtils.equalsInProxy(this.advised, otherAdvised);
}
else {
return false;
}
}
}
// 处理hashCode方法的MethodInterceptor
private static class HashCodeInterceptor implements MethodInterceptor, Serializable {
private final AdvisedSupport advised;
public HashCodeInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
// hashCode方法逻辑
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) {
return CglibAopProxy.class.hashCode() * 13 + this.advised.getTargetSource().hashCode();
}
}
// 处理目标对象是静态的且Advice chain不支持变动的方法的MethodInterceptor
private static class FixedChainStaticTargetInterceptor implements MethodInterceptor, Serializable {
private final List<Object> adviceChain;
@Nullable
private final Object target;
@Nullable
private final Class<?> targetClass;
public FixedChainStaticTargetInterceptor(
List<Object> adviceChain, @Nullable Object target, @Nullable Class<?> targetClass) {
this.adviceChain = adviceChain;
this.target = target;
this.targetClass = targetClass;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
// 创建CglibMethodInvocation
MethodInvocation invocation = new CglibMethodInvocation(
proxy, this.target, method, args, this.targetClass, this.adviceChain, methodProxy);
// MethodInvocation执行时,会先执行完拦截器的逻辑,最后才使用目标对象执行方法
Object retVal = invocation.proceed();
// 处理方法返回值
retVal = processReturnType(proxy, this.target, method, retVal);
return retVal;
}
}
// 处理目标对象是动态的或者Advice chain支持变动的方法的MethodInterceptor
private static class DynamicAdvisedInterceptor implements MethodInterceptor, Serializable {
private final AdvisedSupport advised;
public DynamicAdvisedInterceptor(AdvisedSupport advised) {
this.advised = advised;
}
@Override
@Nullable
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
Object oldProxy = null;
boolean setProxyContext = false;
Object target = null;
TargetSource targetSource = this.advised.getTargetSource();
try {
if (this.advised.exposeProxy) {
// 暴露当前代理
oldProxy = AopContext.setCurrentProxy(proxy);
setProxyContext = true;
}
target = targetSource.getTarget();
Class<?> targetClass = (target != null ? target.getClass() : null);
// 获取拦截器链
List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
Object retVal;
if (chain.isEmpty() && CglibMethodInvocation.isMethodProxyCompatible(method)) {
Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
try {
// 没有配置拦截器,直接使用目标对象执行方法
retVal = methodProxy.invoke(target, argsToUse);
}
catch (CodeGenerationException ex) {
CglibMethodInvocation.logFastClassGenerationFailure(method);
retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
}
}
else {
// 创建CglibMethodInvocation并执行
// MethodInvocation执行时,会先执行完拦截器的逻辑,最后才使用目标对象执行方法
retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
}
// 处理方法返回值
retVal = processReturnType(proxy, target, method, retVal);
return retVal;
}
finally {
if (target != null && !targetSource.isStatic()) {
// 释放目标对象
targetSource.releaseTarget(target);
}
if (setProxyContext) {
// 恢复当前上下文的代理
AopContext.setCurrentProxy(oldProxy);
}
}
}
@Override
public boolean equals(@Nullable Object other) {
return (this == other ||
(other instanceof DynamicAdvisedInterceptor &&
this.advised.equals(((DynamicAdvisedInterceptor) other).advised)));
}
/**
* CGLIB uses this to drive proxy creation.
*/
@Override
public int hashCode() {
return this.advised.hashCode();
}
}
// AOP的MethodInvocation实现子类
private static class CglibMethodInvocation extends ReflectiveMethodInvocation {
@Nullable
private final MethodProxy methodProxy;
public CglibMethodInvocation(Object proxy, @Nullable Object target, Method method,
Object[] arguments, @Nullable Class<?> targetClass,
List<Object> interceptorsAndDynamicMethodMatchers, MethodProxy methodProxy) {
super(proxy, target, method, arguments, targetClass, interceptorsAndDynamicMethodMatchers);
// 仅限非Object的public方法
this.methodProxy = (isMethodProxyCompatible(method) ? methodProxy : null);
}
@Override
@Nullable
public Object proceed() throws Throwable {
try {
return super.proceed();
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
if (ReflectionUtils.declaresException(getMethod(), ex.getClass()) ||
KotlinDetector.isKotlinType(getMethod().getDeclaringClass())) {
// Propagate original exception if declared on the target method
// (with callers expecting it). Always propagate it for Kotlin code
// since checked exceptions do not have to be explicitly declared there.
throw ex;
}
else {
// Checked exception thrown in the interceptor but not declared on the
// target method signature -> apply an UndeclaredThrowableException,
// aligned with standard JDK dynamic proxy behavior.
throw new UndeclaredThrowableException(ex);
}
}
}
@Override
protected Object invokeJoinpoint() throws Throwable {
if (this.methodProxy != null) {
try {
// 优先直接使用目标对象执行方法,比通过反射要略微提升性能
return this.methodProxy.invoke(this.target, this.arguments);
}
catch (CodeGenerationException ex) {
logFastClassGenerationFailure(this.method);
}
}
return super.invokeJoinpoint();
}
static boolean isMethodProxyCompatible(Method method) {
return (Modifier.isPublic(method.getModifiers()) &&
method.getDeclaringClass() != Object.class && !AopUtils.isEqualsMethod(method) &&
!AopUtils.isHashCodeMethod(method) && !AopUtils.isToStringMethod(method));
}
static void logFastClassGenerationFailure(Method method) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to generate CGLIB fast class for method: " + method);
}
}
}
// 为Method分配Callback
private static class ProxyCallbackFilter implements CallbackFilter {
// 返回处理Method的Callback的索引
@Override
public int accept(Method method) {
// finalize方法
if (AopUtils.isFinalizeMethod(method)) {
logger.trace("Found finalize() method - using NO_OVERRIDE");
return NO_OVERRIDE;
}
// Advised接口的方法
if (!this.advised.isOpaque() && method.getDeclaringClass().isInterface() &&
method.getDeclaringClass().isAssignableFrom(Advised.class)) {
if (logger.isTraceEnabled()) {
logger.trace("Method is declared on Advised interface: " + method);
}
return DISPATCH_ADVISED;
}
// equals方法
if (AopUtils.isEqualsMethod(method)) {
if (logger.isTraceEnabled()) {
logger.trace("Found 'equals' method: " + method);
}
return INVOKE_EQUALS;
}
// hashCode方法
if (AopUtils.isHashCodeMethod(method)) {
if (logger.isTraceEnabled()) {
logger.trace("Found 'hashCode' method: " + method);
}
return INVOKE_HASHCODE;
}
Class<?> targetClass = this.advised.getTargetClass();
List<?> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
boolean haveAdvice = !chain.isEmpty();
boolean exposeProxy = this.advised.isExposeProxy();
boolean isStatic = this.advised.getTargetSource().isStatic();
boolean isFrozen = this.advised.isFrozen();
if (haveAdvice || !isFrozen) {
// 如果需要暴露代理,则必须使用DynamicAdvisedInterceptor
if (exposeProxy) {
if (logger.isTraceEnabled()) {
logger.trace("Must expose proxy on advised method: " + method);
}
return AOP_PROXY;
}
// 判断是否存在FixedStaticChainInterceptor可以进行优化
if (isStatic && isFrozen && this.fixedInterceptorMap.containsKey(method)) {
if (logger.isTraceEnabled()) {
logger.trace("Method has advice and optimizations are enabled: " + method);
}
// 使用FixedStaticChainInterceptor进行优化
int index = this.fixedInterceptorMap.get(method);
return (index + this.fixedInterceptorOffset);
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Unable to apply any optimizations to advised method: " + method);
}
// 不存在优化,则使用DynamicAdvisedInterceptor
return AOP_PROXY;
}
}
else {
if (exposeProxy || !isStatic) {
// 需要暴露代理或者目标对象不是静态的
return INVOKE_TARGET;
}
// 判断方法是否可能返回自身
Class<?> returnType = method.getReturnType();
if (targetClass != null && returnType.isAssignableFrom(targetClass)) {
if (logger.isTraceEnabled()) {
logger.trace("Method return type is assignable from target type and " +
"may therefore return 'this' - using INVOKE_TARGET: " + method);
}
// 可能返回自身
return INVOKE_TARGET;
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Method return type ensures 'this' cannot be returned - " +
"using DISPATCH_TARGET: " + method);
}
// 不返回自身
return DISPATCH_TARGET;
}
}
}
}
}
ObjenesisCglibAopProxy
简介
基于Objenesis代理实现的AopProxy
,是CglibAopProxy
的扩展,创建代理对象实例时不通过构造方法;
Spring4默认使用ObjenesisCglibAopProxy
而不是CglibAopProxy
;
核心代码
class ObjenesisCglibAopProxy extends CglibAopProxy {
@Override
protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
// 没有使用构造参数
Class<?> proxyClass = enhancer.createClass();
Object proxyInstance = null;
// 尝试不通过构造方法创建代理对象实例
if (objenesis.isWorthTrying()) {
try {
proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
}
catch (Throwable ex) {
logger.debug("Unable to instantiate proxy using Objenesis, " +
"falling back to regular proxy construction", ex);
}
}
// 未成功创建代理对象实例,则继续通过构造方法创建
if (proxyInstance == null) {
try {
Constructor<?> ctor = (this.constructorArgs != null ?
proxyClass.getDeclaredConstructor(this.constructorArgTypes) :
proxyClass.getDeclaredConstructor());
ReflectionUtils.makeAccessible(ctor);
proxyInstance = (this.constructorArgs != null ?
ctor.newInstance(this.constructorArgs) : ctor.newInstance());
}
catch (Throwable ex) {
throw new AopConfigException("Unable to instantiate proxy using Objenesis, " +
"and regular proxy instantiation via default constructor fails as well", ex);
}
}
((Factory) proxyInstance).setCallbacks(callbacks);
return proxyInstance;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/4783.html