spring-AOP总结

一、spring aop 介绍

二、什么是spring aop以及实现

spring AOP的面向切面编程,是面向对象编程的一种补充,用于处理系统中分布的各个模块的横切关注点,比如说事务管理、日志、缓存等。它是使用动态代理实现的,在内存中临时为方法生成一个AOP对象,这个对象包含目标对象的所有方法,在特定的切点做了增强处理,并回调原来的方法。
Spring AOP的动态代理主要有两种方式实现,JDK动态代理和cglib动态代理。JDK动态代理通过反射来接收被代理的类,但是被代理的类必须实现接口,核心是InvocationHandler和Proxy类。cglib动态代理的类一般是没有实现接口的类,cglib是一个代码生成的类库,可以在运行时动态生成某个类的子类,所以,CGLIB是通过继承的方式做的动态代理,因此如果某个类被标记为final,那么它是无法使用CGLIB做动态代理的。
 spring aop的实现

Spring AOP使用哪种方式实现代理的逻辑在org.springframework.aop.framework.DefaultAopProxyFactory中实现的。

package org.springframework.aop.framework;
 
import java.io.Serializable;
import java.lang.reflect.Proxy;
 
import org.springframework.aop.SpringProxy;
 
@SuppressWarnings("serial")
public class DefaultAopProxyFactory implements AopProxyFactory, Serializable {
 
    @Override
    public AopProxy createAopProxy(AdvisedSupport config) throws AopConfigException {
        if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
            Class<?> targetClass = config.getTargetClass();
            if (targetClass == null) {
                throw new AopConfigException("TargetSource cannot determine target class: " +
                        "Either an interface or a target is required for proxy creation.");
            }
                        //判断如果是接口,或者是被代理的类,则使用JDK动态代理
                        if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
                return new JdkDynamicAopProxy(config);
            }
                        //否则用cglib动态代理,(没有实现接口的类)
                        return new ObjenesisCglibAopProxy(config);
        }
        else {
            //默认使用jdk动态代理
                        return new JdkDynamicAopProxy(config);
        }
    }
 
    /**
    * 确定提供的{@link AdvisedSupport}是否仅有
        * 指定了{@link org.springframework.aop.SpringProxy}接口
        *(或者根本没有指定的代理接口)。
        */
    private boolean hasNoUserSuppliedProxyInterfaces(AdvisedSupport config) {
        Class<?>[] ifcs = config.getProxiedInterfaces();
        return (ifcs.length == 0 || (ifcs.length == 1 && SpringProxy.class.isAssignableFrom(ifcs[0])));
    }
 
}

2、Spring AOP类结构图

最核心的处理是InvocationHandler接口中的invoke()方法

扫描二维码关注公众号,回复: 10559170 查看本文章

三、aop 术语

 

 

 

 

 

 

 

 

 

 

 

 

猜你喜欢

转载自www.cnblogs.com/hellohero55/p/12651933.html