03-AOP

nobility 发布于 2022-03-20 366 次阅读


AOP

AOP(Aspect Orient Programming)面向切面编程,采用横向抽取(代理)机制取代纵向集成体系复用性代码,方便实现对程序进行权限拦截、运行监控等功能

  • Joinpoint(连接点):可以被拦截到的点,也就是方法
  • Pointcut(切入点):真正被拦截到的点,也就是被拦截的方法
  • Advice(通知/增强):拦截后要做的事情,即通知/增强
  • Aspect(切面):切入点和通知的结合
  • Target(目标对象):要被代理的目标对象
  • Weaving(织入):将 通知/增强 应用到目标对象的过程
  • Proxy(代理):被AOP织入、增强后,就会生成一个代理类

Spring传统AOP

动态代理织入,底层采用JDK动态代理(有接口)或CGLib动态代理(无接口),无需专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码

通知类型

  • 前置通知:实现MethodBeforeAdvice接口,实现before()方法
  • 后置通知:实现AfterReturningAdvice接口,实现afterReturning()方法
  • 环绕通知:实现MethodInterceptor接口(aopalliance包中的,而不是Spring框架中的),实现invoke()方法
  • 异常抛出通知:实现ThrowsAdvice接口,编写public void afterThrowing(Exception e)方法,程序有异常时才会执行该方法
package com;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

import java.lang.reflect.Method;

public class MyAdvice implements MethodBeforeAdvice, AfterReturningAdvice, MethodInterceptor, ThrowsAdvice {
  @Override
  public void before(Method method, Object[] objects, Object o) {
    System.out.println("前置通知");
  }

  @Override
  public void afterReturning(Object o, Method method, Object[] objects, Object o1) {
    System.out.println("后置通知");
  }

  @Override
  public Object invoke(MethodInvocation methodInvocation) throws Throwable {
    System.out.println("前:环绕通知");
    Object proceed = methodInvocation.proceed();  //执行原来的方法,也可以不执行
    System.out.println("后:环绕通知");
    return proceed;
  }

  public void afterThrowing(Exception e) {
    System.out.println("异常抛出通知" + e);
  }
}

切面类型

一般切面

Advisor:通知本身就是一个切面,对目标类所有方法进行拦截,配置ProxyFactoryBean代理类工厂对象

<bean id="userService" class="com.UserServiceImpl"/>  <!--目标类,要被代理的类-->
<bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->

<bean id="userServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  <!--代理类-->
  <property name="target" ref="userService"/>  <!--指定要代理的目标类-->
  <property name="interceptorNames" value="myAdvice"/>  <!--指定拦截器,即指定要织入的通知类,注意这里是value属性指定其他bean的ID-->
  <property name="proxyInterfaces" value="com.UserService" />  <!--指定目标类实现的接口,若是多个接口使用list>value标签指定,可以不写由Spring自动选择-->
  
  <property name="singleton" value="false"/>  <!--代理类对象设置为多例模式,默认单例-->
  
  <!--下面中有一个设置为true,都会使用CGLib代理-->
  <property name="proxyTargetClass" value="true"/> <!--使用类代理,而不是接口,即使用CGLib代理-->
  <property name="optimize" value="true"/>  <!--使用CGLib代理-->
</bean>

下面是测试代码

public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userServiceProxy");  //此时获取代理类对象
  userService1.hello();
  userService1.world();
}
带切点的切面

PointcutAdvisor:切面是切入点和通知的结合,指定拦截目标类的哪些方法,配置RegexpMethodPointcutAdvisor正则方法切入点通知,再配置ProxyFactoryBean代理类工厂对象

<bean id="userService" class="com.UserServiceImpl"/>  <!--目标类,要被代理的类-->
<bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->

<bean id="myAspect" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  <!--构造正则表达式切面-->
  <property name="pattern" value=".*hello.*"/>  <!--使用正则进行方法名匹配,注意若加入包名时,点需要转义-->
  <property name="advice" ref="myAdvice"/>
</bean>

<bean id="userServiceProxy" class="org.springframework.aop.framework.ProxyFactoryBean">  <!--代理类-->
  <property name="target" ref="userService"/>
  <property name="interceptorNames" value="myAspect"/>  <!--指定拦截器,即指定切面,注意这里是value属性指定其他bean的ID-->
</bean>

下面是测试代码

public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userServiceProxy");  //此时获取代理类对象
  userService1.hello();
  userService1.world();
}

自动代理

基于bean名称的自动代理

配置BeanNameAutoProxyCreatorBean名称自动代理构造器,或对目标类所有方法进行拦截,无法对单个方法拦截

原理是使用实现了BeanPostProcessor接口,IOC中的生命周期中postProcessBeforeInitialization()方法和postProcessAfterInitialization()方法进行的代理,所以直接获取原Bean即可

<bean id="userService" class="com.UserServiceImpl"/>   <!--目标类,要被代理的类-->
<bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">  <!--代理类-->
  <property name="beanNames" value="user*"/>  <!--要自动代理的beanID,可使用星号通配符-->
  <property name="interceptorNames" value="myAdvice"/>  <!--拦截器使用的通知类,要织入的类-->
</bean>

下面是测试代码

public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");  //获取原对象即可
  userService1.hello();
  userService1.world();
}
基于切面信息的自动代理

加入DefaultAdvisorAutoProxyCreator默认切面自动代理构造器即可

原理是使用实现了BeanPostProcessor接口,IOC中的生命周期中postProcessBeforeInitialization()方法和postProcessAfterInitialization()方法进行的代理,所以直接获取原Bean即可

<bean id="userService" class="com.UserServiceImpl"/>  <!--目标类,要被代理的类-->
<bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->

<bean id="myAspect" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">  <!--构造正则表达式切面-->
  <property name="pattern" value="com\.UserService\.hello"/>  <!--这次使用包名,准确匹配,注意若加入包名时,点需要转义-->
  <property name="advice" ref="myAdvice"/>
</bean>

<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
<!--加入该类即可无需多余配置,会自动根据切面信息进行自动代理-->

下面是测试代码

public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");  //获取原对象即可
  userService1.hello();
  userService1.world();
}

AspectJ的AOP

编译期织入和类装载期织入,AspectJ是一个基于Java语音的AOP框架,Spring2.0之后就新增了对AspectJ切点表达式的支持,spring-aspects

通知类型

定义一个普通类,不强制实现任何接口,但是作为通知的方法最好保证一定结构(一些参数,若不需要使用可以无视)

  • 前置通知:xml中使用before标签,对应@Before注解
  • 后置通知:xml中使用after-returning标签,对应@AfterReturning注解
  • 环绕通知:xml中使用around标签,对应@Around注解
  • 异常抛出通知:xml中使用after-throwing标签,对应@AfterThrowing注解
  • 最终通知:xml中使用after标签,对应@After注解,不管是否出错都会执行
package com;

import org.aspectj.lang.ProceedingJoinPoint;

public class MyAdvice {
  public void before() {
    System.out.println("前置通知");
  }

  public void afterReturning(Object result) {
    System.out.println("后置通知,原来方法的返回值为:" + result);
  }

  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("前:环绕通知");
    Object proceed = joinPoint.proceed();
    System.out.println("后:环绕通知");
    return proceed;
  }

  public void afterThrowing(Throwable e) {
    System.out.println("异常抛出通知" + e);
  }

  public void after() {
    System.out.println("最终通知");
  }
}

切入点表达式

用于描述切入点的表达式,类似一个函数,使用execution()定位定位到方法,语法为execution(方法上的注解 方法修饰符 返回值类型 方法名(参数类型列表) throws 异常类型列表)(空格隔开)

  • 注解:可省,比如废弃注解@Deprecated,不常用,好像只能使用java.lang包中的注解
  • 方法修饰符:可省,比如public
  • 返回值类型:不可省,使用星号通配符表示任意返回值类型
  • 方法名:不可省
    • com.*:com包下的所有类中的所有方法(不包括子包)
    • com..*:com包下的所有类中的所有方法(包括子包)
    • com.UserServiceImpl.*:UserServiceImpl类中的所有方法
    • com.UserService+.*:UserService接口及其子类中的所有方法
    • com.UserServiceImpl.hello*:UserServiceImpl类中以hello开头的方法
    • com.UserServiceImpl.*hello:UserServiceImpl类中以hello结尾的方法
    • com.UserServiceImpl.*hello*:UserServiceImpl类中包含hello方法
  • 参数类型列表:括号不可省
    • ():表示无参
    • (*):一个任意类型的参数,(*,*)就代表两个任意类型的参数
    • (..):任意个任意类型的参数
    • (..,String):最后一个参数是String类型,(String,..)就代表第一个参数是String类型
    • (*,String):共两个参数,第二个参数是String类型,(String,*)就代表共两个参数,第一个参数是String类型
    • (String):共一个参数,并且是String类型
  • 异常类型列表:可省,不常用,可使用星号通配符

xml方式

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
  <!--
  首先添加 xmlns:aop="http://www.springframework.org/schema/aop" 约束文件
  再在 xsi:schemaLocation属性后增加 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
  之后使用下面标签才能有代码提示
  -->
  <bean id="userService" class="com.UserServiceImpl"/>  <!--目标类,要被代理的类-->
  <bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->

  <aop:config>  <!--配置AspectJ的aop-->
    <!--pointcut标签配置切入点-->
    <aop:pointcut id="pointcut" expression="execution(* com.UserServiceImpl.hello(..))"/>

    <!--aspect标签配置切面-->
    <aop:aspect ref="myAdvice"> <!--ref指定通知类,标签内指定通知方法是哪种通知类型,以及对应的切点,pointcut可指定自己的切点,pointcut-ref可引用定义好的切点-->
      <aop:before method="before" pointcut="execution(* com.UserServiceImpl.hello(..))"/>  <!--前置通知-->
      <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>  <!--后置通知,returning属性值对应该方法中的result参数名-->
      <aop:around method="around" pointcut-ref="pointcut"/>  <!--环绕通知-->
      <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>  <!--异常抛出通知,throwing属性值对应方法中的e参数名-->
      <aop:after method="after" pointcut-ref="pointcut"/>  <!--最终通知-->
    </aop:aspect>
  </aop:config>
</beans>

注解方式

首先需要在Spring-Framework全局配置文件中开启AspectJ自动代理,具体如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
  <!--
  首先添加 xmlns:aop="http://www.springframework.org/schema/aop" 约束文件
  再在 xsi:schemaLocation属性后增加 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd
  之后使用下面标签才能有代码提示
  -->
  <aop:aspectj-autoproxy/>  <!--开启AspectJ自动代理-->
  <bean id="userService" class="com.UserServiceImpl"/>  <!--目标类,要被代理的类-->
  <bean id="myAdvice" class="com.MyAdvice"/>  <!--通知类,要织入的类-->
</beans>

使用注解配置通知类

package com;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

@Aspect
public class MyAdvice {
  @Before("execution(* com.UserServiceImpl.hello(..))")
  public void before() {
    System.out.println("前置通知");
  }

  @AfterReturning(value = "execution(* com.UserServiceImpl.hello(..))", returning = "result")
  public void afterReturning(Object result) {
    System.out.println("后置通知,原来方法的返回值为:" + result);
  }

  @Around("execution(* com.UserServiceImpl.hello(..))")
  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("前:环绕通知");
    Object proceed = joinPoint.proceed();
    System.out.println("后:环绕通知");
    return proceed;
  }

  @AfterThrowing(value = "execution(* com.UserServiceImpl.hello(..))", throwing = "e")
  public void afterThrowing(Throwable e) {
    System.out.println("异常抛出通知" + e);
  }

  @After("execution(* com.UserServiceImpl.hello(..))")
  public void after() {
    System.out.println("最终通知");
  }
}

对于相同切点,可使用@Pointcut注解为其命名(必须定义一个空方法),方便其他地方引用,引用时调用其使用@Pointcut的空方法即可,具体如下

package com;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;

@Aspect
public class MyAdvice {
  @Pointcut("execution(* com.UserServiceImpl.hello(..))")
  private void pointcut() {}  //定义的空方法,用于@Pointcut切点命名

  @Before("pointcut()")  //其他通知类型注解直接调用该空方法即可
  public void before() {
    System.out.println("前置通知");
  }

  @AfterReturning(value = "pointcut()", returning = "result")
  public void afterReturning(Object result) {
    System.out.println("后置通知,原来方法的返回值为:" + result);
  }

  @Around("pointcut()")
  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    System.out.println("前:环绕通知");
    Object proceed = joinPoint.proceed();
    System.out.println("后:环绕通知");
    return proceed;
  }

  @AfterThrowing(value = "pointcut()", throwing = "e")
  public void afterThrowing(Throwable e) {
    System.out.println("异常抛出通知" + e);
  }

  @After("pointcut()")
  public void after() {
    System.out.println("最终通知");
  }
}

xml方式和注解方式的测试方法

public static void main(String[] args) {
  ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
  UserService userService1 = (UserService) applicationContext.getBean("userService");  //获取原对象即可,必须从容器中获取
  userService1.hello();
  userService1.world();
}
此作者没有提供个人介绍
最后更新于 2022-03-20