Spring AOP小记

it2022-05-05  104

AOP

1.aop是spring框架的核心概念之一,用于对类的方法进行增强,分为静态增强和动态增强.

  基本概念

动态增强是基于jdk自身的动态代理和cglib动态代理.目标对象 -->target 需要增强的目标对象 (目标类)切点 -->pointCut 目标类中的方法(method),当切点是实现了父接口中的方法时,使用java的动态代理,当方法不属于接口时,使用 cglib的动态代理切面 -->aspect    多个切点和通知共同组成的切面,aspect = piontCut + advice;通知 -->advice    增强的内容  (以下是基于spring传统的AOP接口) 分为前置增强(MethodBeforeAdvice),后置增强(AfterRunningAdvice),环绕增强(MethodInterceptor),是org.aopalliance.intercept.MethodInterceptor包下   代理 -->Proxy

1.jdk proxy

  Object obj  = Proxy.newProxyInstance(classLoder,Class[] interfaces,InvocationHandler h);

2.cglib proxy

  Enhancer enhancer = new Enhancer();

  enhancer.setSupperClass(target.class);

  enhancer.callback(new MethodInterceptor())

  Object obj  = enhancer.create();

jdk自带的动态代理有明显的缺点,cglib的相对来说比jdk自带的强悍点,不管目标类有没有实现接口,都可以增强

 第一种: 基于传统的spring的AOP需要实现上述的几个接口,在bean.xml中配置

  <bean id="target" class="your target class" />

  <bean id="advice" class="your advice class"/>

  <aop:config>

  <aop:pointcut expression="execution(* *(..))" id="pointId">

  <aop:advisor advice-ref="advice" pointcut-ref="piontId">

  </aop:config>

第二种: 基于aspectJ框架的AOP

    增强类不用实现接口,有一点需要特别注意:

    在写环绕增强的方法时,需要一个形参proceedingJoinPoint pjp

    在bean.xml中配置如下:

  <bean id="target" class="your target class" />

 

  <bean id="advice" class="your advice class"/>

 

  <aop:config>

 

  <aop:aspect ref="advice">

    <aop:pointcut expression="execution(* *(..))" id="pointId">

    <aop:before method="beforeMethodName" pointcut-ref="pointId">

    <aop:around method="aroundMethodName" pointcut-ref="pointId">

  </aop:aspect>

 

  </aop:config>

第三种:基于注解形式的AOP

  @Aspect   --->声明该类为切面类

  @Before(aspect的表达式)   --->说明这个前置增强的方法要作用在什么类上

  @AfterRunning(aspect的表达式)  --->说明这个后置增强的方法要作用在什么类上

  @Around(aspect的表达式) --->说明这个环绕增强的方法要作用在什么类上

  最后在bean.xml中配置注解的自动扫描和        AOP注解的类的代理<aop:aspectj-autoproxy/>

 

总结:

  注意点: 在使用AOP增强时首先要确定切面,(目标对象+增强方法),

      当声明了多个切面的时候,order属性决定了切面的执行顺序,order为正整数,取值越小则优先级越高

      传统、基于框架、注解的增强的执行顺序是不一样的,使用时要注意

      spring默认情况下是优先使用jdk的动态代理,但当目标对象没有实现接口是才会使用cglib的动态代理;

 

转载于:https://www.cnblogs.com/zhaiwei/p/9470289.html


最新回复(0)