为什么SpringAOP使用JDK动态代理时好像没有代理Object.[equals()、hashCode()、toString()]这三个方法

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dzgt10076/article/details/52833156

*

Spring的AOP是通过JDK动态代理或者CGLib来生成目标对象的代理对象,然后将增强功能(Aspect【包括了Advice和Pointcut】)织入到符合条件(Pointcut)的类的方法(JoinPoint)上。

*
JDK动态代理实现原理 http://rejoy.iteye.com/blog/1627405


//这是JDK动态代理过程中要代理的4个方法
 private static Method m1;
 private static Method m3;
 private static Method m0;
 private static Method m2;

 m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
 m3 = Class.forName("pers.mine.SpringAOP.vo.KongFuInterface").getMethod("random", new Class[0]);
 m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
 m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);

但是spring代理过程中并没有将相应代码插入[equals()、hashCode()、toString()]三个方法中,为什么呢?
答案在org.springframework.aop.framework.JdkDynamicAopProxy类中
这个类实现了InvocationHandler接口,说明SpringAOP是通过这个类实现动态代理的
在这个类的invoke方法中有

try {
            if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
                // The target does not implement the equals(Object) method itself.
                return equals(args[0]);
            }
            else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
                // The target does not implement the hashCode() method itself.
                return hashCode();
            }
            else if (method.getDeclaringClass() == DecoratingProxy.class) {
                // There is only getDecoratedClass() declared -> dispatch to proxy config.
                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...
                return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
            }

            Object retVal;

            if (this.advised.exposeProxy) {
                // Make invocation available if necessary.
                oldProxy = AopContext.setCurrentProxy(proxy);
                setProxyContext = true;
            }

            // May be null. Get as late as possible to minimize the time we "own" the target,
            // in case it comes from a pool.
            target = targetSource.getTarget();
            if (target != null) {
                targetClass = target.getClass();
            }

            // Get the interception chain for this method.
            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()) {
                // We can skip creating a MethodInvocation: just invoke the target directly
                // Note that the final invoker must be an InvokerInterceptor so we know it does
                // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
                Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
                retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
            }
            else {
                // We need to create a method invocation...
                invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
                // Proceed to the joinpoint through the interceptor chain.
                retVal = invocation.proceed();
            }

            // Massage return value if necessary.
            Class<?> returnType = method.getReturnType();
            if (retVal != null && retVal == target && returnType.isInstance(proxy) &&
                    !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
                // Special case: it returned "this" and the return type of the method
                // is type-compatible. Note that we can't help if the target sets
                // a reference to itself in another returned object.
                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()) {
                // Must have come from TargetSource.
                targetSource.releaseTarget(target);
            }
            if (setProxyContext) {
                // Restore old proxy.
                AopContext.setCurrentProxy(oldProxy);
            }
        }

可以看到一开始开始使用if语句过滤了equals()、hashCode()两个方法
toString()有点特殊[先写到这,后续细究吧]。。。

展开阅读全文

hashCode(),equals()和compareTo()这三个方法的执行顺序

05-31

Student.javarn[code=Java]rnimport java.util.*;rnpublic class Studentrnrn public static void main(String[] args)rn rn Set set=new TreeSet();rn Hash_Set hs=new Hash_Set();rn Hash_Set hs2=new Hash_Set();rn Hash_Set hs3=new Hash_Set();rn Hash_Set hs4=new Hash_Set();rn rn hs.setId(01);rn hs.setName("li");rn rn hs2.setId(02);rn hs2.setName("wang");rn rn hs3.setId(03);rn hs3.setName("zhang");rn rn hs4.setId(01);rn hs4.setName("li");rn rn set.add(hs);rn set.add(hs2);rn set.add(hs3);rn set.add(hs4);rn Iterator it=set.iterator();rn while(it.hasNext())rn rn Object obj=it.next();rn Hash_Set hs5=(Hash_Set)obj;rn System.out.println(hs5.getId()+":"+hs5.getName());rn rn rnrnrn[/code]rnrnTest_Set.javarn[code=Java]rnimport java.util.*;rnpublic class Test_Set implements Comparablernrn private int id;rn private String name;rn rn public int getId() rn return id;rn rn public void setId(int id) rn this.id = id;rn rn public String getName() rn return name;rn rn public void setName(String name) rn this.name = name;rn rn public int hashCode()rn rn return id;rn rn public boolean equals(Object obj)rn rn if(obj==null)rn rn return false;rn rn if(obj instanceof Test_Set)rn rn Test_Set hs=(Test_Set)obj;rn if(id==hs.id)rn rn if(this.name==hs.name)rn return true;rn rn rn return false;rn rn public int compareTo(Object obj)rn rn int result=0;rn System.out.println("id:"+id); //这个打印出来是:3 3 1 1rn System.out.println(((Test_Set)obj).id); //这个打印出来是:1 2 2 1,为什么id和(((Test_Set)obj).id是这样的数字?rn if(obj!=null && obj instanceof Test_Set)rn rn Test_Set hs=(Test_Set)obj;rn if(id>hs.id)rn result=1;rn else if(id 论坛

没有更多推荐了,返回首页