一、前言
关于spring的spring-test源码包中org.springframework.test.util.AopTestUtils测试AOP工具类(AopUtils),通过对象获取代理目标getTargetObject注入对象实例,详情参见源码说明部分。
二、源码说明
package org.springframework.test.util;@b@@b@import org.springframework.aop.TargetSource;@b@import org.springframework.aop.framework.Advised;@b@import org.springframework.aop.support.AopUtils;@b@import org.springframework.util.Assert;@b@@b@public abstract class AopTestUtils@b@{@b@ public static <T> T getTargetObject(Object candidate)@b@ {@b@ Assert.notNull(candidate, "Candidate must not be null");@b@ try {@b@ if ((AopUtils.isAopProxy(candidate)) && (candidate instanceof Advised))@b@ return ((Advised)candidate).getTargetSource().getTarget();@b@ }@b@ catch (Throwable ex)@b@ {@b@ throw new IllegalStateException("Failed to unwrap proxied object", ex);@b@ }@b@ return candidate;@b@ }@b@@b@ public static <T> T getUltimateTargetObject(Object candidate)@b@ {@b@ Assert.notNull(candidate, "Candidate must not be null");@b@ try {@b@ if ((AopUtils.isAopProxy(candidate)) && (candidate instanceof Advised))@b@ return getUltimateTargetObject(((Advised)candidate).getTargetSource().getTarget());@b@ }@b@ catch (Throwable ex)@b@ {@b@ throw new IllegalStateException("Failed to unwrap proxied object", ex);@b@ }@b@ return candidate;@b@ }@b@}