(1)AOP概念:面向切面编程:扩展功能不修改源代码实现
AOP采用横向抽取机制,取代传统的纵向继承体系重复性代码(性能监视,事务管理,安全检查,缓存)
(动态代理实现)
AOP操作术语:
(JoinPoint)连接点:类里面可以被增强的方法
(Pointcut)切入点:实际增强的方法,也就是新增的方法
(Advice)通知/增强:增强的逻辑,比如扩展日志功能,这个日志功能增强
前置通知、后置通知、异常通知、最终通知、环绕通知
(Aspect)切面:把增强应用到具体方法上,过程称为切面
AOP操作准备
1.导入AOP相关jar包
aopalliance-1.0.jar
aspectjweaver-1.8.7.jar
spring-aop.RELEASE.jar
spring-aspects-RELEASE.jar
2.创建spring核心配置文件,导入aop约束spring-aop.xsd
3.使用表达式配置切入点
(1)切入点:实际增强的方法
(2)常用的表达式
execution(方法修饰符 方法返回值 方法所属类 匹配方法名(方法中的形参表) 方法申明抛出的异常)
`execution(*空格com.Book.add(..)) add()方法
`execution(*空格com.Book.*(..)) 类中的所有方法
`execution(*空格*.*(..)) 所有类中的所有方法
`execution(*空格save*(..)) 匹配所有以save开头的方法名
<!--配置文件中-->
<bean id="" class="">
<!--配置aop操作-->
<aop:config>
<!--配置切入点-->
<aop:pointcut expression="execution(*空格com.aop.Book.*(..)) id="pointcut1(切入点名字)">
<!--配置切面 把增强用到方法上-->
<aop:aspect ref="增强类对象的id" >
<!--配置增强类型 method:增强类使用在哪个方法上作为前置-->
<aop:before method="before1" pointcut-ref="pointcut1"/>
<!--后置通知-->
<aop:after-returning method="after1" pointcut-ref="pointcut1"/>
<!--环绕通知-->
<aop:around method="around1" pointcut-ref="pointcut1"/>
</aop:aspect>
</aop:config>
测试:环绕通知
public void around(ProceedingJoinPoint proceedingJoinPoint){
//方法之前代码
//执行要被增强的方法
proceedingJoinPoint.proceed();
//方法之后代码
}