一、AOP织入配置
<aop:config>
<!-- 声明切面 -->
<aop:aspect ref="切面类id">
<!-- 抽取切点表达式 -->
<aop:pointcut id="切点id" expression="切点表达式"/>
<!-- 设置增强 -->
<aop:增强方式 method="增强方法名" pointcut-ref="切点id"></aop:增强方式>
</aop:aspect>
</aop:config>
二、切点表达式写法
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
访问修饰符可以省略
返回值类型、包名、方法名可以使用星号(*)代表任意
包名与类名之间一个点.代表当前包下的类,两个点..表示当前包及其子包下的类
参数列表可以使用两个点..表示任意参数个数及类型的参数
示例:execution(* *..*.*(..)) 表示任意返回值类型的任意包及其子包下的任意类的任意参数的任意方法
三、5种(通知/增强)的类型
<aop:通知类型 method="切面类中的方法名" pointcut="切点表达式"></aop:通知类型>
各种增强除执行时机不同,标签不同和环绕增强多出一个参数,其他配置基本相同。
public class Aspect {
// 前置增强
public void TargetBefor() {
System.out.println("Target befor method");
}
// 后置增强
public void TargetAfter() {
System.out.println("Target after method");
}
// 环绕增强
// 与其他增强不同,多了一个ProceedingJoinPoint参数用于调用切点以完成环绕增强
public Object Around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("环绕前");
// 执行切电方法
Object process = pjp.proceed();
System.out.println("环绕后");
return process;
}
}
<bean id="AspectId" class="com.syx.Aspect"/>
<aop:config>
<!-- 声明切面 -->
<aop:aspect ref="AspectId">
<!-- 设置后置增强 -->
<aop:after method="TargetAfter" pointcut="execution(public void com.syx.TargetImpl.testTarget())"></aop:after>
<!-- 设置前置增强 -->
<aop:before method="TargetBefor" pointcut="execution(public void com.syx.TargetImpl.testTarget())"></aop:before>
<!-- 设置环绕增强 -->
<aop:around method="Around" pointcut="execution(public void com.syx.TargetImpl.testTarget())"></aop:around>
</aop:aspect>
</aop:config>
四、切点表达式的抽取
可以将切点表达式抽取出来为一个对象,设置增强时使用pointcut-ref去引用该切点表达式
使用切点表达式后,上面例子中的配置文件会变为如下形式:
<bean id="AspectId" class="com.syx.Aspect"/>
<aop:config>
<!-- 声明切面 -->
<aop:aspect ref="AspectId">
<!-- 抽取切点表达式 -->
<aop:pointcut id="pointcutId" expression="execution(public void com.syx.TargetImpl.testTarget())"/>
<!-- 设置后置增强 -->
<aop:after method="TargetAfter" pointcut-ref="pointcutId"></aop:after>
<!-- 设置前置增强 -->
<aop:before method="TargetBefor" pointcut-ref="pointcutId"></aop:before>
<!-- 设置环绕增强 -->
<aop:around method="Around" pointcut-ref="pointcutId"></aop:around>
</aop:aspect>
</aop:config>