面向切面的编程,是面向对象编程(oop)的补充。把公共代码抽取出来在需要的地方重新调用,公共代码例如日志、事务、安全处理等。公共代码称为切面(aspect),引入公共代码的操作称为织入;引入切面的方法称为切入点(joinpoint);
一、引入切面的通知方式:
before:前置通知
after-returning:后置通知
around:环绕通知
throws:异常通知 after-throwing
after:最终通知,不管如何都执行(有异常通知的情况下也会执行,类似finally)
二、applicationContext.xml配置方式:
1、配置监视类、切面类。
2、配置spring aop代理,配置切入点,织入切面,在监视类中调用切入点方法时调用切面方法。异常通知时需要添加throwing参 数。
<!-- 1、配置监视类 -->
<bean id="chitu" class="com.aaa.vo.ChiTu">
</bean>
<!-- 2、配置切面类 -->
<bean id="zcb" class="com.aaa.vo.ZcbAspect"></bean>
<!-- 3、配置spring aop代理 -->
<aop:config>
<!-- 配置切入点,对应方法表达式,何时去监视对象 注意表达式execution(方法名),方法中的参数是参数的类型 -->
<aop:pointcut expression="execution(void run(int))" id="p1"/>
<!-- 织入切面 ref:需要织入的切面名称 , method:切面类中的方法名 , pointcut-ref:切入点引用的是哪个 -->
<aop:aspect ref="zcb">
<aop:before method="before" pointcut-ref="p1"/> 前置通知
<aop:after-returning method="after" pointcut-ref="p1"/> 后置通知
<aop:after-throwing method="exception" pointcut-ref="p1" throwing="e"/> 异常通知
<aop:around method="around" pointcut-ref="p1"/> 环绕通知
<aop:after method="afterEnd" pointcut-ref="p1"/> 最终通知
</aop:aspect>
</aop:config>
切面类:
切面类中的方法需要获取切入点参数JoinPoint,在切入点参数中使用getArgs获取切入点方法的参数列表,getSignature().getName()获取切入点的方法名
//前置通知
public void before(JoinPoint jp){
Object[] args = jp.getArgs();//方法参数数组
String methodName = jp.getSignature().getName();//方法名称
if("run".equals(methodName)){
Integer juli = (Integer) args[0];
if(juli < 50){
System.out.println("报警,关于来了"+"距离"+juli);
}
}