首页

关于spring-test包中AopTestUtils面向切面测试工具类获取注入目标对象测试代码示例

标签:spring-test,AopTestUtils,面向切面测试工具类,AopUtils,springframework,TargetSource,Advised     发布时间:2018-09-13   

一、前言

关于springspring-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@}