Skip to content

九、AOP

一、什么是AOP

介绍

AOPAspect Oriented Programming的缩写,意思为面向切面编程,是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP是 OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

1、AOP 的作用及其优势

详细信息
  • 作用:在程序运行期间,在不修改源码的情况下对方法进行功能增强
  • 优势:减少重复代码,提高开发效率,并且便于维护

2、AOP的底层实现

详细信息

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

3、AOP 的动态代理技术

常用的动态代理技术

  • JDK代理:基于接口的动态代理技术
  • cglib代理:基于父类的动态代理技术

4、AOP相关概念

提示

  • Target(目标对象):代理的目标对象
  • Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类
  • Joinpoint(连接点):所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点
  • Pointcut(切入点)所谓切入点是指我们要对哪些Joinpoint进行拦截的定义
  • Advice(通知/增强):所谓通知是指拦截到Joinpoint之后所要做的事情就是通知
  • Aspect(切面):是切入点和通知(引介)的结合
  • Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而Aspect采用编译期织入和类装载期织入

二、xml方式实现aop

1、快速上手


(1)创建TargetInterface接口

java
public interface TargetInterface {
    public void save();
}

(2)实现TargetInterface接口的Target类

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

(3)创建MyAspect切面类

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

(4) 配置Spring XML文件applicationContext.xml

xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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/aop http://www.springframework.org/schema/aop/spring-aop.xsd
">
    <bean id="target" class="org.example.aop.Target"></bean>

    <bean id="myAspect" class="org.example.aop.MyAspect"></bean>

    <aop:config>
        <aop:aspect ref="myAspect">
            <aop:before method="before" pointcut="execution(public void org.example.aop.Target.save())"/>
        </aop:aspect>
    </aop:config>
</beans>

(5)测试AOP配置

java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class aopTest {

    @Autowired
    private TargetInterface target;

    @Test
    public void test() {
        target.save();
    }
}

2、配置aop详解


(1)切点表达式的写法

表达式语法

java
execution([修饰符 ]返回值类型.包名.类名.方法名(参数))
  • 访问修饰符可以省略
  • 返回值类型、包名、类名、方法名可以使用星号*代表任意
  • 包名与类名之间一个点.代表当前包下的类,两个点..表示当前包及其子包下的类
  • 参数列表可以使用两个点..表示任意个数,任意类型的参数列表
java
execution(public void com.itheima.aop.Target.method ())
execution(void com.itheima.aop.Target.*(..))
execution(* com.itheima.aop.*.*(..))
execution(* com.itheima.aop..*.*(..))
execution(* *..*.* (..))

(2)通知的类型

配置语法

java
<aop:通知类型 method="切面类中方法名" pointcut="切点表达式"></aop:通知类型>
名称标签说明
前置通知<aop:before>用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知<aop:after-returning>用于配置后置通知。指定增强的方法在切入点方法之后执行
环绕通知<aop:around>用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行
异常抛出通知<aop:throwing>用于配置异常抛出通知。指定增强的方法在出现异常时执行
最终通知<aop:after>用于配置最终通知。无论增强方式执行是否有异常都会执行
java
public class MyAspect {
	public void before() {
    	System.out.println("前置增强...");
	}
}
xml
<aop:config>
    <aop:aspect ref="myAspect">
        <aop:before method="before" pointcut="execution(public void org.example.aop.Target.save())"/>
    </aop:aspect>
</aop:config>
java
public class Target implements TargetInterface{
    @Override
    public void save() {
        System.out.println("save...");
    }
}
前置增强...
save...
  • after-returning
java
public class MyAspect {
	public void afterReturning() {
    	System.out.println("后置增强...");
	}
}
xml
<aop:config>
    <aop:aspect ref="myAspect">
       	<aop:after-returning method="afterReturning" pointcut="execution(public void org.example.aop.Target.save())"/>
    </aop:aspect>
</aop:config>
java
public class Target implements TargetInterface{
    @Override
    public void save() {
        System.out.println("save...");
    }
}
save...
后置增强...
java
public class MyAspect {
	public Object around(ProceedingJoinPoint pjp) throws Throwable {
  	System.out.println("环绕前增强...");
  	Object proceed = pjp.proceed();
  	System.out.println("环绕后增强...");
  	return proceed;
  }
}
xml
<aop:config>
    <aop:aspect ref="myAspect">
       <aop:around method="around" pointcut="execution(public void org.example.aop.Target.save())"/>
    </aop:aspect>
</aop:config>
java
public class Target implements TargetInterface{
    @Override
    public void save() {
        System.out.println("save...");
    }
}
环绕前增强...
save...
环绕后增强...
java
public class MyAspect {
	public void afterThrowing() {
      System.out.println("异常抛出增强...");
  }
}
xml
<aop:config>
    <aop:aspect ref="myAspect">
       <aop:after-throwing method="afterThrowing" pointcut="execution(public void org.example.aop.Target.save())"/>
    </aop:aspect>
</aop:config>
java
public class Target implements TargetInterface{
    @Override
    public void save() {
    	int i=1/0;
        System.out.println("save...");
    }
}
异常抛出增强...
java.lang.ArithmeticException: / by zero
......
java
public class MyAspect {
	public void after() {
  	System.out.println("最终结束增强...");
  }
}
xml
<aop:config>
    <aop:aspect ref="myAspect">
       <aop:after method="after" pointcut="execution(public void org.example.aop.Target.save())"/>
    </aop:aspect>
</aop:config>
java
public class Target implements TargetInterface{
    @Override
    public void save() {
        System.out.println("save...");
    }
}
save...
最终结束增强...

(3)通知执行顺序

前置增强...
环绕前增强...
save...
最终结束增强...
环绕后增强...
后置增强...

(4)切点表达式的抽取

xml
<aop:config>
    <aop:aspect ref="myAspect">
        <aop:pointcut id="myPointcut" expression="execution(public void org.example.aop.Target.save())"/>
        
        <aop:before method="before" pointcut-ref="myPointcut"/>
        <aop:after-returning method="afterReturning" pointcut-ref="myPointcut"/>
        <aop:around method="around" pointcut-ref="myPointcut"/>
        <aop:after-throwing method="afterThrowing" pointcut-ref="myPointcut"/>
        <aop:after method="after" pointcut-ref="myPointcut"/>
    </aop:aspect>
</aop:config>

三、注解方式实现aop

1、快速上手


(1)创建TargetInterface接口

java
package org.example.annoAop;

public interface TargetInterface {
    public void save();
}

(2)实现TargetInterface接口的Target类

java
@Component("target")
public class Target implements TargetInterface {

    @Override
    public void save() {
        System.out.println("save...");
    }
}

(3)创建MySpect切面类

java
@Component("myAspect")
@Aspect
public class MyAspect {

    @Before("execution(* org.example.annoAop.*.*(..))")
    public void before() {
        System.out.println("前置增强...");
    }
}

(4)配置Spring XML文件applicationContext.xml

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="org.example.annoAop"/>

    <!--    aop自动代理-->
    <aop:aspectj-autoproxy/>

</beans>

(5)测试AOP配置

java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext-anno.xml")
public class AnnoAopTest {


    @Autowired
    private TargetInterface target;

    @Test
    public void test() {
        target.save();
    }

}

2、配置aop详解

通知的配置语法:@通知注解("切点表达式")

名称标签说明
前置通知@Before用于配置前置通知。指定增强的方法在切入点方法之前执行
后置通知@AfterReturning用于配置后置通知。指定增强的方法在切入点方法之后执行
环绕通知@Around用于配置环绕通知。指定增强的方法在切入点方法之前和之后都执行
异常抛出通知@AfterThrowing用于配置异常抛出通知。指定增强的方法在出现异常时执行
最终通知@After用于配置最终通知。无论增强方式执行是否有异常都会执行

(1)通知的类型

切面类Aspect

java
@Component("myAspect")
@Aspect
public class MyAspect {

    @Before("execution(* org.example.annoAop.*.*(..))")
    public void before() {
        System.out.println("前置增强...");
    }

    @AfterReturning("execution(* org.example.annoAop.*.*(..))")
    public void afterReturning() {
        System.out.println("后置增强...");
    }

    @Around("execution(* org.example.annoAop.*.*(..))")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强...");

        Object proceed = pjp.proceed();

        System.out.println("环绕后增强...");

        return proceed;
    }

    @AfterThrowing("execution(* org.example.annoAop.*.*(..))")
    public void afterThrowing() {
        System.out.println("异常抛出增强...");
    }

    @After("execution(* org.example.annoAop.*.*(..))")
    public void after() {
        System.out.println("最终结束增强...");
    }
}

(2)切点表达式的抽取

java
@Component("myAspect")
@Aspect
public class MyAspect {
    @Pointcut("execution(* org.example.annoAop.*.*(..))") 
    public void pointcut() { 
    } 

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

    @AfterReturning("pointcut()")
    public void afterReturning() {
        System.out.println("后置增强...");
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前增强...");

        Object proceed = pjp.proceed();

        System.out.println("环绕后增强...");

        return proceed;
    }

    @AfterThrowing("pointcut()")
    public void afterThrowing() {
        System.out.println("异常抛出增强...");
    }

    @After("pointcut()")
    public void after() {
        System.out.println("最终结束增强...");
    }
}