佳林L

博客园 首页 新随笔 联系 订阅 管理

Spring-Aop

● AOP(概念):

什么是AOP?

○ Aspect Oriented Programming 面向切面编程,利用Aop可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

AOP(术语):

○ 连接点:类里面那些方法可以被增强,这些方法称为连接点。

○ 切入点:实际被真正增强的方法,称为切入点。

○ 通知(增强):实际增加的那个逻辑部分称为通知。

通知分为:前置,后置,环绕,异常,最终。

○ 切面:是动作,把通知应用到切入点的过程。

AOP操作:

○ Spring框架一般都是基于 AspectJ 实现AOP操作。

* 什么是AspectJ?

AspectJ不是Spring组成部分,独立AOP框架,一般把 AspectJ 和 Spring框架一起使用,进行AOP操作。

○ 基于AspectJ实现AOP操作:

① 基于xml配置文件。

② 基于注解方式实现。

○ 切入点表达式:

① 作用:知道对那个类里面的那个方法进行增强。

② 语法结构:execution([权限修饰符],[返回类型],[类全路径],[方法名称],[参数列表])。

● AOP操作(AspectJ注解):

    //前置通知
   @Before(value = "execution(* com.djl.aop.User.add(..))")
   public void before(){
       System.out.println("before...");
  }

   //后置通知
   @AfterReturning(value = "execution(* com.djl.aop.User.add(..))")
   public void afterReturning(){
       System.out.println("afterReturning...");
  }

   //环绕通知
   @Around(value = "execution(* com.djl.aop.User.add(..))")
   public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
       System.out.println("around之前...");
       proceedingJoinPoint.proceed();
       System.out.println("around之后...");
  }

   //最终通知
   @After(value = "execution(* com.djl.aop.User.add(..))")
   public void after(){
       System.out.println("after...");
  }
   
   //异常通知
   @AfterThrowing(value = "execution(* com.djl.aop.User.add(..))")
   public void afterThrowing(){
       System.out.println("afterThrowing...");
  }

● 相同切入点抽取:

    @Pointcut(value = "execution(* com.djl.bean.Persen.eat(..))")
   public void spring12(){

  }

   @Before(value = "spring12()")
   public void eat(){
       System.out.println("student eat...");
  }

 

● 有多个增强类对同一方法进行增强,设置增强类优先级:

○ 在增强类上加上注解 @order( 数字类型值 ),数字类型值越小优先级越高

@Component
@Aspect
@Order(value = 1)
public class Persenproxy {

   @Before(value = "execution(* com.djl.aop.User.add(..))")
   public void before(){
       System.out.println("persen before....");
  }
}

● 使用配置文件实现AOP操作:

        <!-- 创建对象 -->
       <bean id="student" class="com.djl.aopxml.Student"></bean>
       <bean id="persen" class="com.djl.aopxml.Persen"></bean>

       <!-- 配置aop增强 -->
       <aop:config>
               <!-- 配置切入点 -->
               <aop:pointcut id="a" expression="execution(* com.djl.aopxml.Student.eat(..))"/>
               <!-- 配置切面 -->
               <aop:aspect ref="persen">
                       <aop:before method="before" pointcut-ref="a"></aop:before>
               </aop:aspect>
       </aop:config>

● 完全基于注解:

@Configuration
@ComponentScan(basePackages = {"com.djl.aopxml"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class comfig {
}

 

posted on 2020-09-18 13:47  佳林L  阅读(103)  评论(0编辑  收藏  举报