Spring--SpringAOP核心类

发布于:2022-12-05 ⋅ 阅读:(390) ⋅ 点赞:(0)

一,核心类介绍

Spring AOP 有很多相关类,如:ProxyFactory、ProxyCreatorSupport、AdvisedSupport、ProxyConfig。而Spring AOP其中核心类则是 ProxyCreatorSupport,此类主要功能是初始化具体的动态代理。而 AdvisedSupport、ProxyConfig 的主要是围绕 AOP 相关配置进行封装。

核心类关系图

核心类作用

说明

AopInfrastructureBean

标记接口。用来表明该Bean是Spring AOP基础类。这意味着即使切点匹配,任何此类Bean都不会被自动代理。

Avised

AOP代理工厂配置类接口。此配置包括Interceptor、Advice、Advisor和代理接口。 从Spring获得的任何AOP代理都可以转换为该接口,以便进行相关Aop操作。

AvisedSupport

AOP代理配置管理类。该类可以配置当前代理的Adivsiors、目标对象、代理的接口,以及获取对应代理方法对应有效的拦截器链。本类本身不提供创建代理的方法,而用于生成拦截器链和保存代理快照。

ProxyConfig

用于创建代理的配置类,以确保所有代理创建者具有一致的属性。该类主要为AOP代理对象工厂实现类提供基本的配置属性

ProxyProcessSupport

代理处理器常用功能的基类

AbstractAutoProxyCreator

自动代理创建器的抽象实现。该类的作用是使用AOP代理包装每个合格的Bean,并在调用Bean之前委派指定的拦截器。

AbstractAdvisorAutoProxyCreator

通用自动代理创建器。根据检测到的每个Advisor为特定的Bean构建AOP代理。

DefaultAdvisorAutoProxyCreator

基于当前BeanFactory中的所有候选 Advisor 来创建AOP代理。换句话来说,该类的作用就是扫描上下文找出所有Advisor,并将这些Advisor应用到所有符合切入点的Bean中。

ProxyCreatorSupport

代理工厂的基类。提供对可配置AopProxyFactory的便捷访问,如:注册和触发监听器、创建AopProxy等

ProxyFactory

AOP代理工厂(以编程方式使用,而不是通过声明式使用)

IntroductionAdvisor

Spring中有五种增强:

  • BeforeAdvide(前置增强)

  • AfterAdvice(后置增强)

  • ThrowsAdvice(异常增强)

  • RoundAdvice(环绕增强)

  • IntroductionAdvice

前四种增强大家都非常熟悉,而第五种可能大家还不太熟悉。Introduction Advice意为引入增强,Spring将其视为一种特殊的拦截 Advice。引入增强涉及到的中主要类有 IntroductionAdvisor 和 IntroductionInterceptor:

// 引入拦截器
// 该类的目的是为目标对象添加新的属性和行为必须声明相应的接口以及相应的实现。
// 再通过特定的拦截器将新的接口定义以及实现类中的逻辑附加到目标对象上
// 而后,目标对象(确切的说,是目标对象的代理对象)就拥有了新的状态和行为
public interface IntroductionInterceptor extends MethodInterceptor, DynamicIntroductionAdvice {

}

public interface IntroductionAdvisor extends Advisor, IntroductionInfo {

    ClassFilter getClassFilter();

    void validateInterfaces() throws IllegalArgumentException;
}

// 引入信息。该接口描述了目标类需要实现的新接口
public interface IntroductionInfo {

    Class[] getInterfaces();
}

换句话来讲:引入增强的意思即假如项目中一个Java类没有实现某个接口而不具备某些功能,这个时候我们可以使用引入增强(Introduction Advice)在不修改这个类的前提下,使该类具备某个接口的功能。

示例1:

interface Rent {
    void preRent();
    void postRent();
}

public class IntroductionInterceptorDemo implements IntroductionInterceptor, Lockable {
    @Override
    public void preRent() {
        System.out.println("出租前.......");
    }

    @Override
    public void postRent() {
        System.out.println("出租后.......");
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (implementsInterface(invocation.getMethod().getDeclaringClass())){
            return invocation.getMethod().invoke(this, invocation.getArguments());
        }
        return invocation.proceed();
    }

    @Override
    public boolean implementsInterface(Class<?> intf) {
        // 判断是否是Lockable接口的实现类
        return intf.isAssignableFrom(Lockable.class);
    }

    public static void main(String[] args) {
        ProxyFactory factory = new ProxyFactory(new Landlord());
        factory.setProxyTargetClass(true);

        // 声明IntroductionInterceptor引入增强拦截器
        Advice advice = new IntroductionInterceptorDemo();

        // 声明Advisor
        Advisor advisor = new DefaultIntroductionAdvisor((DynamicIntroductionAdvice) advice,
                Lockable.class);
        factory.addAdvisor(advisor);

        Lockable lockable = (Lockable) factory.getProxy();
        lockable.preRent();

        Landlord landlord = (Landlord) factory.getProxy();
        // 调用Landlord自身的方法
        landlord.rent();
        lockable.postRent();
    }
}

示例2(使用DelegatingIntroductionInterceptor类)

public class IntroductionDelegationDemo extends DelegatingIntroductionInterceptor
        implements Lockable {

    private static final long serialVersionUID = 1L;

    @Override
    public void preRent() {
        System.out.println("出租前.......");
    }

    @Override
    public void postRent() {
        System.out.println("出租后.......");
    }

    public static void main(String[] args) {
        ProxyFactory factory = new ProxyFactory(new Landlord());
        factory.setProxyTargetClass(true);

        // 声明IntroductionInterceptor引入增强拦截器
        Advice advice = new IntroductionDelegationDemo();

        // 声明Advisor
        Advisor advisor = new DefaultIntroductionAdvisor((IntroductionDelegationDemo) advice,
                Lockable.class);
        factory.addAdvisor(advisor);

        Lockable lockable = (Lockable) factory.getProxy();
        lockable.preRent();

        Landlord landlord = (Landlord) factory.getProxy();
        // 调用Landlord自身的方法
        landlord.rent();
        lockable.postRent();
    }
}

二,核心类源码

AbstractAutoProxyCreator

protected Object createProxy(
			Class<?> beanClass, String beanName, Object[] specificInterceptors, TargetSource targetSource) {

    if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
        AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
    }

    // 创建ProxyFactory对象。代理对象主要由工厂创建
    ProxyFactory proxyFactory = new ProxyFactory();
    // 向proxyFactory里拷贝必要的属性,如:proxyTargetClass
    proxyFactory.copyFrom(this);

    // 判断是否直接代理目标类以及任何接口
    if (!proxyFactory.isProxyTargetClass()) {
        // 判断是否使用给定的Bean替代其目标类而不是接口
        if (shouldProxyTargetClass(beanClass, beanName)) {
            // 设置true直接代理目标类
            proxyFactory.setProxyTargetClass(true);
        }
        else {
            // 检查Bean上的接口,筛选合理的代理接口,否则返回目标类代理
            evaluateProxyInterfaces(beanClass, proxyFactory);
        }
    }

    // 获取Advisor接口的特定拦截器以及公共拦截器
    Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
    // 将所有给定的Advisor添加到代理配置中
    proxyFactory.addAdvisors(advisors);
    // 将目标对象添加到代理配置中
    proxyFactory.setTargetSource(targetSource);
    // 该函数为空方法。可以由子类覆盖为代理配置设置一些自定义配置
    customizeProxyFactory(proxyFactory);

    // 是否应冻结配置
    // 冻结配置后无法Advice。这样可以避免调用者在转换为Advised之后仍然能够操纵配置
    proxyFactory.setFrozen(this.freezeProxy);
    if (advisorsPreFiltered()) {
        proxyFactory.setPreFiltered(true);
    }

    // 返回代理代理对象
    return proxyFactory.getProxy(getProxyClassLoader());
}

ProxyProcessSupport

public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {

	// 检查Bean上的接口,并将它们应用于ProxyFactory
    // Bean是否具有合理的接口,会调用isConfigurationCallbackInterfaceisInternalLanguageInterface来进行筛选
	protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {
        // 获取Bean的所有接口
		Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());
        // 是否是一个合理的接口
		boolean hasReasonableProxyInterface = false;
        // 遍历所有的接口
		for (Class<?> ifc : targetInterfaces) {
            // 检测是否是一个合理的接口
			if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&
					ifc.getMethods().length > 0) {
				hasReasonableProxyInterface = true;
				break;
			}
		}

		if (hasReasonableProxyInterface) {
			// 如果是一个合理的接口,简单的Add到存放所有Interface的List中(表示后续用JDK动态代理处理)
			for (Class<?> ifc : targetInterfaces) {
				proxyFactory.addInterface(ifc);
			}
		}
		else {
            // 使用CGLib来处理
			proxyFactory.setProxyTargetClass(true);
		}
	}

	// 确定接口是否是容器回调(符合这些条件的不会被视为不合理的代理接口)
	protected boolean isConfigurationCallbackInterface(Class<?> ifc) {
		return (InitializingBean.class == ifc || DisposableBean.class == ifc ||
				Closeable.class == ifc || "java.lang.AutoCloseable".equals(ifc.getName()) ||
				ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class));
	}

	// 确定接口是否符合其他语言的接口(符合这些条件的被视为不合理的代理接口)
    // 如果未找到Bean的合理代理接口,则将其完整目标类作为代理对象
	protected boolean isInternalLanguageInterface(Class<?> ifc) {
		return (ifc.getName().equals("groovy.lang.GroovyObject") ||
				ifc.getName().endsWith(".cglib.proxy.Factory") ||
				ifc.getName().endsWith(".bytebuddy.MockAccess"));
	}
}

AbstractAdvisorAutoProxyCreator

public abstract class AbstractAdvisorAutoProxyCreator extends AbstractAutoProxyCreator {

    // 用于从BeanFactory中搜索Spring Advisor的工具类
	private BeanFactoryAdvisorRetrievalHelper advisorRetrievalHelper;

	@Override
    // 重写父类的setBeanFactory
	public void setBeanFactory(BeanFactory beanFactory) {
		super.setBeanFactory(beanFactory);
        // 必须为ConfigurableListableBeanFactory
		if (!(beanFactory instanceof ConfigurableListableBeanFactory)) {
			throw new IllegalArgumentException(
					"AdvisorAutoProxyCreator requires a ConfigurableListableBeanFactory: " + beanFactory);
		}
        // 初始化beanFactory
        // 基于搜索到的Advisor为特定Bean构建AOP代理
		initBeanFactory((ConfigurableListableBeanFactory) beanFactory);
	}

	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		this.advisorRetrievalHelper = new BeanFactoryAdvisorRetrievalHelperAdapter(beanFactory);
	}


    // 覆盖父类的方法。目的是找到对应Bean的切点方法
	@Override
	protected Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName, TargetSource targetSource) {
        // 获取合格的Advisor集合
		List<Advisor> advisors = findEligibleAdvisors(beanClass, beanName);
		if (advisors.isEmpty()) {
			return DO_NOT_PROXY;
		}
		return advisors.toArray();
	}

    // 为自动代理类查找所有合格的Advisors
	protected List<Advisor> findEligibleAdvisors(Class<?> beanClass, String beanName) {
        // 获取所有Advisor候选
		List<Advisor> candidateAdvisors = findCandidateAdvisors();
        // 对所有的候选Advisor进行筛选,找到符合的Advisor
		List<Advisor> eligibleAdvisors = findAdvisorsThatCanApply(candidateAdvisors, beanClass, beanName);
        // 对符合的Advisor进行扩展操作(见extendAdvisors方法)
		extendAdvisors(eligibleAdvisors);
		if (!eligibleAdvisors.isEmpty()) {
            // 对符合的Advisor进行排序
			eligibleAdvisors = sortAdvisors(eligibleAdvisors);
		}
		return eligibleAdvisors;
	}

    // 查找要在自动代理中使用的所有候选Advisors
	protected List<Advisor> findCandidateAdvisors() {
		return this.advisorRetrievalHelper.findAdvisorBeans();
	}

    // 搜索给定的候选Advisor,以查找到可以应用于指定Bean的所有Advisor
	protected List<Advisor> findAdvisorsThatCanApply(
			List<Advisor> candidateAdvisors, Class<?> beanClass, String beanName) {

		ProxyCreationContext.setCurrentProxiedBeanName(beanName);
		try {
			return AopUtils.findAdvisorsThatCanApply(candidateAdvisors, beanClass);
		}
		finally {
			ProxyCreationContext.setCurrentProxiedBeanName(null);
		}
	}

    // 返回具有给定名称的Advisor Bean是否符合代理资格
	protected boolean isEligibleAdvisorBean(String beanName) {
		return true;
	}

    // 对Advisors进行排序(默认根据Order进行排序)
	protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
		AnnotationAwareOrderComparator.sort(advisors);
		return advisors;
	}

	// 该方法可以由子类覆盖,以便注册管理(增删改等操作)其他Advisors
	protected void extendAdvisors(List<Advisor> candidateAdvisors) {
	}

	@Override
	protected boolean advisorsPreFiltered() {
		return true;
	}

	// BeanFactoryAdvisorRetrievalHelper子类
	private class BeanFactoryAdvisorRetrievalHelperAdapter extends BeanFactoryAdvisorRetrievalHelper {

		public BeanFactoryAdvisorRetrievalHelperAdapter(ConfigurableListableBeanFactory beanFactory) {
			super(beanFactory);
		}

		@Override
		protected boolean isEligibleBean(String beanName) {
			return AbstractAdvisorAutoProxyCreator.this.isEligibleAdvisorBean(beanName);
		}
	}
}

ProxyFactory

public class ProxyFactory extends ProxyCreatorSupport {

    // 创建代理工厂
    public ProxyFactory(Object target) {
        // 设置被代理的目标对象
        setTarget(target);
        // 设置代理接口
        setInterfaces(ClassUtils.getAllInterfaces(target));
    }

    // 创建代理工厂
    // 没有被代理的目标对象,只有接口。所以必须增加拦截器
    public ProxyFactory(Class<?>... proxyInterfaces) {
        // 设置代理接口
        setInterfaces(proxyInterfaces);
    }

    // 创建代理工厂
    public ProxyFactory(Class<?> proxyInterface, Interceptor interceptor) {
        // 设置代理接口
        addInterface(proxyInterface);
        // 设置拦截器
        addAdvice(interceptor);
    }

   // 创建代理工厂
    public ProxyFactory(Class<?> proxyInterface, TargetSource targetSource) {
        // 设置代理接口
        addInterface(proxyInterface);
        // 设置被代理的目标对象
        setTargetSource(targetSource);
    }
}

AopUtils

// 判断给定的切点(Poincut)是否可以完全应用于给定的类(targetClass)
public static boolean canApply(Pointcut pc, Class<?> targetClass, boolean hasIntroductions) {
    Assert.notNull(pc, "Pointcut must not be null");
    // 切点的类过滤器如果和目标类不匹配,返回false
    if (!pc.getClassFilter().matches(targetClass)) {
        return false;
    }

    MethodMatcher methodMatcher = pc.getMethodMatcher();
    // 如果是MethodMatcher.TRUE(总是匹配),则不需要迭代方法直接返回true
    if (methodMatcher == MethodMatcher.TRUE) {
        return true;
    }

    IntroductionAwareMethodMatcher introductionAwareMethodMatcher = null;
    // 是否为IntroductionAwareMethodMatcher实例
    if (methodMatcher instanceof IntroductionAwareMethodMatcher) {
        introductionAwareMethodMatcher = (IntroductionAwareMethodMatcher) methodMatcher;
    }

    // Set用于存放给定类(targetClass)的所有接口,包括由超类实现的接口
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>(ClassUtils.getAllInterfacesForClassAsSet(targetClass));
    // 将targetClass目标类也放入Set中
    classes.add(targetClass);
    for (Class<?> clazz : classes) {
        // 获取所有方法
        Method[] methods = ReflectionUtils.getAllDeclaredMethods(clazz);
        for (Method method : methods) {
            // 方法匹配判断。如果匹配则返回true
            if ((introductionAwareMethodMatcher != null &&
                 introductionAwareMethodMatcher.matches(method, targetClass, hasIntroductions)) ||
                methodMatcher.matches(method, targetClass)) {
                return true;
            }
        }
    }

    return false;
}

// 确定适用于给定类的候选Advisor集合
public static List<Advisor> findAdvisorsThatCanApply(List<Advisor> candidateAdvisors, Class<?> clazz) {
    // 候选Advisor列表为空,直接返回
    if (candidateAdvisors.isEmpty()) {
        return candidateAdvisors;
    }

    // 候选Advisor列表不为空,则进行候选Advisor筛选
    List<Advisor> eligibleAdvisors = new LinkedList<Advisor>();
    for (Advisor candidate : candidateAdvisors) {
        // 判断候选Advisor是否适用于给定的类
        if (candidate instanceof IntroductionAdvisor && canApply(candidate, clazz)) {
            // 适用于给定类的Advisor添加到eligibleAdvisors集合中
            eligibleAdvisors.add(candidate);
        }
    }
    boolean hasIntroductions = !eligibleAdvisors.isEmpty();
    for (Advisor candidate : candidateAdvisors) {\
        // 如果为IntroductionAdvisor在上面已经处理过
        if (candidate instanceof IntroductionAdvisor) {
            // already processed
            continue;
        }

		// 非IntroductionAdvisor再进行匹配工作(执行canApply)
        if (canApply(candidate, clazz, hasIntroductions)) {
            eligibleAdvisors.add(candidate);
        }
    }
    return eligibleAdvisors;
}

 

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到