Spring的AOP

151 阅读7分钟

Spring的AOP简介

AOP的概念

AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。 AOP 是 OOP 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP的作用和优势

作用:在程序运行期间在不修改源码的情况下对方法进行功能增强

优势:减少重复代码,提高开发效率,并且便于维护

AOP完成动态结合,暂时可以理解为:切面=目标方法(save方法)+功能增强方法(日志控制),如下图所示 image.png

AOP的底层实现--动态代理技术

AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入在去调用目标对象的方法,从而完成功能的增强

动态代理技术

JDK 代理 : 基于接口的动态代理技术

cglib 代理:基于父类的动态代理技术 image.png

JDK 代理

//目标类接口
public interface TargetInterface {
public void method(); 
}
//目标类
public class Target implements TargetInterface {
    @Override
    public void method() {
    System.out.println("Target running...."); 
    }
}
//动态代理代码
Target target = new Target(); //创建目标对象 
//创建代理对象
TargetInterface proxy = (TargetInterface) Proxy.newProxyInstance(target.getClass() .getClassLoader(),target.getClass().getInterfaces(),new InvocationHandler() {
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) 
    throws Throwable {
    System.out.println("前置增强代码..."); 
    Object invoke = method.invoke(target, args); 
    System.out.println("后置增强代码..."); 
    return invoke;
    } 
});
// 调用代理对象的方法测试
// 测试,当调用接口的任何方法时,代理对象的代码都无序修改
proxy.method();

image.png

cglib 代理

//目标类
public class Target {
    public void method() {
    System.out.println("Target running...."); 
    }
}
动态代理代码
Target target = new Target(); //创建目标对象
Enhancer enhancer = new Enhancer();   //创建增强器 
enhancer.setSuperclass(Target.class); //设置父类 
enhancer.setCallback(new MethodInterceptor() { //设置回调
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("前置代码增强....");
        Object invoke = method.invoke(target, objects); 
        System.out.println("后置代码增强....");
        return invoke; 
    }
});
Target proxy = (Target) enhancer.create(); //创建代理对象
//测试,当调用接口的任何方法时,代理对象的代码都无序修改
proxy.method();

image.png

AOP的相关概念

我们必须理解 AOP 的相关术语,常用的术语如下:
      Target(目标对象):代理的目标对象
      Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
      Joinpoint(连接点):所谓连接点是指那些被拦截到的点,通俗理解:可以被增强的方法。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
      Pointcut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义。
              通俗理解:切入点是实际上被真正增强的方法,连接点不一定都能被增强,只是可以增强
      Advice(通知/增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知,就是在原本方法上增强的那一段方法,比如日志控制
      Aspect(切面):是切入点和通知(引介)的结合
      Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入

AOP开发需要明确的事项

1. 需要编写的内容

  •   编写核心业务代码(目标类的目标方法)
    
  •   编写切面类,切面类中有通知(增强功能方法)
    
  •   在配置文件中,配置织入关系,即将哪些通知与哪些连接点进行结合
    

2. AOP 技术实现的内容

Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。

3. AOP 底层使用哪种代理方式

在 spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。

基于xml的AOP开发

快速入门的步骤

  • 导入 AOP 相关坐标
  • 创建目标接口和目标类(内部有切点)
  • 创建切面类(内部有增强方法)
  • 将目标类和切面类的对象创建权交给 spring
  • 在 applicationContext.xml 中配置织入关系
  • 测试代码

导入 AOP 相关坐标

<!--spring核心容器包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.5</version>
    </dependency>
<!--    aspectjweaver切面织入-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.7</version>
    </dependency>

创建目标接口和目标类(内部有切点)

public interface TargetInterface {
    public void save();
}
public class Target implements TargetInterface {
    @Override
    public void save() {
        System.out.println("save is running....");
    }
}

创建切面类(内部有增强方法)

public class MyAspect {

    public void before(){
        System.out.println("前置增强...");
    }

}

将目标类和切面类的对象创建权交给 spring && 在 applicationContext.xml 中配置织入关系

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <context:component-scan base-package="com.kkk.aop"></context:component-scan>
<!--    目标对象-->
    <bean id="target" class="com.kkk.aop.Target"/>
<!--    切面对象 -->
    <bean id="MyAspect" class="com.kkk.aop.MyAspect"/>
<!--    配置织入:告诉spring框架,哪些方法(切点)需要进行那些增强(前置、后置...)-->
    <aop:config>
<!--        声明切面-->
        <aop:aspect ref="MyAspect">
            <!--     切面=切点+通知-->
            <!--     告诉spring是前置增强,before()方法是前置增强,切点(切点表达式)是save()方法-->
            <aop:before method="before" pointcut="execution(public void com.kkk.aop.Target.save())"></aop:before>
        </aop:aspect>
    </aop:config>
</beans>

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
   @Autowired
   private TargetInterface target;
   @Test
    public void test1(){
        target.save();
   }
}

结果:

image.png

XML 配置 AOP 详解

切点表达式的写法

表达式通用语法:`execution([修饰符] 返回值类型 包名.类名.方法名(参数))`
1. 访问修饰符可以省略
2. 返回值类型、包名、类名、方法名可以使用星号*  代表任意
3. 包名与类名之间一个点 . 代表当前包下的类,两个点 .. 表示当前包及其子包下的类
4. 参数列表可以使用两个点 .. 表示任意个数,任意类型的参数列表 
例如:
//不通用
execution(public void com.itheima.aop.Target.method())
//Target类下的所有方法都会被增强
execution(void com.itheima.aop.Target.*(..))
//常用:aop包下的任意类下的任一方法
execution(* com.itheima.aop.*.*(..))
//aop包及其子包下的任意类下的任一方法
execution(* com.itheima.aop..*.*(..))
//了解,无意义
execution(* *..*.*(..))

通知的类型

image.png 举例:

public class MyAspect {

    public void before(){
        System.out.println("前置增强...");
    }
    public void after(){
        System.out.println("后置增强...");
    }
    //ProceedingJoinPoint:正在执行的连接点--切点
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强");
        Object proceed = pjp.proceed(); //切点方法
        System.out.println("环绕后增强");
        return  proceed;
    }

}
<!--    配置织入:告诉spring框架,哪些方法(切点)需要进行那些增强(前置、后置...)-->
    <aop:config>
<!--        声明切面-->
        <aop:aspect ref="MyAspect">
            <!--     切面=切点+通知-->
            <!--     告诉spring是前置增强,before()方法是前置增强,切点(切点表达式)是save()方法-->
            <aop:before method="before" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:before>
            <aop:after-returning method="after" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:after-returning>
            <aop:around method="around" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:around>
        </aop:aspect>
    </aop:config>

运行结果:

image.png

切点表达式的抽取

当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替 pointcut 属性来引用抽取后的切点表达式 举例:

  • 原本的配置织入写法:pointcut中的切点表达式都相同
<!--    配置织入:告诉spring框架,哪些方法(切点)需要进行那些增强(前置、后置...)-->
    <aop:config>
<!--        声明切面-->
        <aop:aspect ref="MyAspect">
            <!--     切面=切点+通知-->
            <!--     告诉spring是前置增强,before()方法是前置增强,切点(切点表达式)是save()方法-->
            <aop:before method="before" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:before>
            <aop:after-returning method="after" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:after-returning>
            <aop:around method="around" pointcut="execution(* com.kkk.aop.*.*(..))"></aop:around>
        </aop:aspect>
    </aop:config>

  • 现在的配置织入写法,将pointcut中相同的切点表达式进行抽取
<!--    配置织入:告诉spring框架,哪些方法(切点)需要进行那些增强(前置、后置...)-->
    <aop:config>
<!--        声明切面-->
        <aop:aspect ref="MyAspect">
            <!--抽取切点表达式-->
            <aop:pointcut id="myPointcut" expression="execution(* com.kkk.aop.*.*(..))"/>
            <!--     切面=切点+通知-->
            <!--     告诉spring是前置增强,before()方法是前置增强,切点(切点表达式)是save()方法-->
            <aop:before method="before" pointcut-ref="myPointcut"></aop:before>
            <aop:after-returning method="after" pointcut-ref="myPointcut"></aop:after-returning>
            <aop:around method="around" pointcut-ref="myPointcut"></aop:around>
        </aop:aspect>
    </aop:config>

基于注解的AOP开发

  • 创建目标接口和目标类(内部有切点)
  • 创建切面类(内部有增强方法)
  • 将目标类和切面类的对象创建权交给 spring
  • 在切面类中使用注解配置织入关系,使用@Aspect标注切面类,使用@通知注解标注通知方法
  • 在配置文件中开启组件扫描和 AOP 的自动代理aop:aspectj-autoproxy/
  • 测试

通知注解类型

image.png

举例

//测试类接口
public interface TargetInterface {
    public void save();
}
//测试类
//扫描组件
@Component("target")
public class Target implements TargetInterface {
    @Override
    public void save() {
        System.out.println("save is running....");
    }
}
//切面类
@Component("myAspect")
@Aspect //标注该myAspect类是一个切面类
public class MyAspect {
    //配置前置增强
    @Before("execution(* com.kkk.anno.*.*(..))")
    public void before(){
        System.out.println("前置增强...");
    }
    public void after(){
        System.out.println("后置增强...");
    }
    //ProceedingJoinPoint:正在执行的连接点--切点
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强");
        Object proceed = pjp.proceed(); //切点方法
        System.out.println("环绕后增强");
        return  proceed;
    }
}
spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--       组件扫描-->
    <context:component-scan base-package="com.kkk.anno"/>
<!--    配置aop的动态代理-->
    <aop:aspectj-autoproxy/>

</beans>
//测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoTest {
    @Autowired
    private TargetInterface target;
    @Test
    public void test(){
        target.save();
    }
}

测试结果

image.png

切点表达式的抽取--@pointcut()

@Component("myAspect")
@Aspect //标注该myAspect类是一个切面类
public class MyAspect {

    //配置前置增强
    @Before("myPoint()")
    public void before(){
        System.out.println("前置增强...");
    }
    @AfterReturning("MyAspect.myPoint()")
    public void after(){
        System.out.println("后置增强...");
    }
    @Pointcut("execution(* com.kkk.anno.*.*(..))")
    //定义切点表达式
    public void myPoint(){}
}

同xml配置aop一样,我们可以将切点表达式抽取。抽取方式是 在切面内定义方法 ,在该方法上使用 @Pointcut 注解定义切点表达式,然后在在增强注解中进行引用。具体如下: