springAOP面向切面编程

165 阅读2分钟

AOP简介

image.png

AOP相关术语

Jpinpoint连接点

是指能被拦截的点,在spring中只有方法能被拦截。

Pointcut切点

指要对哪些连接点进行拦截,即被增强的方法

Advice通知

指拦截后要做的事情,即被拦截后需要执行的方法

Aspect切面

切点+通知称为切面

AspectJ是一个基于Java语言的AOP框架,在Spring框架中建议使用AspectJ实现AOP

AOP的通知类型

image.png

各个通知的配置文件的写法
<!-- 配置AOP -->
<aop:config>
   <!-- 配置切面 -->
   <aop:aspect ref="myAspectJAdvice">
       <!-- 配置切点 -->
       <aop:pointcut id="myPointcut" expression="execution(*com.itbaizhan.dao.UserDao.*(..))"/>
       <!-- 前置通知 -->
       <aop:before method="myBefore" pointcut-ref="myPointcut"></aop:before>
       <!-- 后置通知 -->
       <aop:after-returning method="myAfterReturning" pointcut-ref="myPointcut"/>
       <!-- 异常通知 -->
       <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointcut" throwing="ex"/>
       <!-- 最终通知 -->
       <aop:after method="myAfter" pointcut-ref="myPointcut"></aop:after>
       <!-- 环绕通知 -->
       <aop:around method="myAround" pointcut-ref="myPointcut"></aop:around>
   </aop:aspect>
</aop:config>

切点表达式的写法

标准写法:访问修饰符 返回值 包名.类名.方法名(参数列表)

访问修饰符可以省略。

返回值使用 * 代表任意类型。

包名使用 * 表示任意包,多级包结构要写多个 * ,使用 *.. 表示任意包结构

类名和方法名都可以用 * 实现通配。

参数列表

  • 基本数据类型直接写类型
  • 引用类型写 包名.类名
  • *表示匹配一个任意类型参数
  • .. 表示匹配任意类型任意个数的参数

全通配: * ...*(..)

多切面配置

即在配置AOP的标签<aop:config>中再配置一个切面<aop:aspect ref=" ">

注解配置AOP

  • 在xml文件中开启AOP注解支持<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  • 在通知类上方加入注解@Aspect
  • 在通知方法上加入注解@Before/@AfterReturning/@AfterThrowing/@After/@Around 分别为前置通知,后置通知,异常通知,最后通知,环绕通知. 注解括号里要加入切点表达式
如何为一个类下的所有方法配置切点

在通知类中添加方法配置切点

  • 使用注解Pointcut
@Pointcut("execution(*com.itbaizhan.dao.UserDao.*(..))")
public void pointCut(){}

然后直接在通知的注解中加入"pointCut()"即可

配置类如何代替XML中的AOP注解支持

在配置类上方添加@EnableAspectJAutoProxy即可

然后读取配置文件的时候直接读取该配置类即可