aop之AspectJ学习

一、  介绍

l  AspectJ是一个基于Java语言的AOP框架

l  Spring2.0以后新增了对AspectJ切点表达式支持

l  @AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面

新版本Spring框架,建议使用AspectJ方式来开发AOP

l  主要用途:自定义开发


二、  切入点表达式【掌握】

1.execution()  用于描述方法【掌握】

       语法:execution(修饰符 返回值  包.类.方法名(参数) throws异常)

              修饰符,一般省略

                     public            公共方法

                     *                   任意

              返回值,不能省略

                     void               返回没有值

                     String            返回值字符串

                     *                  任意

              包,[省略]

                     com.itheima.crm                  固定包

                     com.itheima.crm.*.service     crm包下面子包任意(例如:com.itheima.crm.staff.service)

                     com.itheima.crm..                crm包下面的所有子包(含自己)

                     com.itheima.crm.*.service..   crm包下面任意子包,固定目录service,service目录任意包

              类,[省略]

                     UserServiceImpl                  指定类

                     *Impl                                  以Impl结尾

                     User*                                  以User开头

                     *                                        任意

              方法名,不能省略

                     addUser                               固定方法

                     add*                                          以add开头

                     *Do                                    以Do结尾

                     *                                        任意

              (参数)

                     ()                                        无参

                     (int)                                    一个整型

                     (int,int)                              两个

                     (..)                                      参数任意

              throws,可省略,一般不写。

综合1

       execution(* com.itheima.crm.*.service..*.*(..))

综合2

       <aop:pointcutexpression="execution(* com.itheima.*WithCommit.*(..)) ||

                          execution(* com.itheima.*Service.*(..))"id="myPointCut"/>

2.within:匹配包或子包中的方法(了解)

       within(com.itheima.aop..*)

3.this:匹配实现接口的代理对象中的方法(了解)

       this(com.itheima.aop.user.UserDAO)

4.target:匹配实现接口的目标对象中的方法(了解)

       target(com.itheima.aop.user.UserDAO)

5.args:匹配参数格式符合标准的方法(了解)

       args(int,int)

6.bean(id) 对指定的bean所有的方法(了解)

       bean('userServiceId')

三、  AspectJ 通知类型

l  aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。

l  aspectj 通知类型,只定义类型名称。已经方法格式。

l  个数:6种,知道5种,掌握1中。

       before:前置通知(应用:各种校验)

              在方法执行前执行,如果通知抛出异常,阻止方法运行

       afterReturning:后置通知(应用:常规数据处理)

              方法正常返回后执行,如果方法中抛出异常,通知无法执行

              必须在方法执行后才执行,所以可以获得方法的返回值。

       around:环绕通知(应用:十分强大,可以做任何事情)

              方法执行前后分别执行,可以阻止方法的执行

              必须手动执行目标方法

       afterThrowing:抛出异常通知(应用:包装异常信息)

              方法抛出异常后执行,如果方法没有抛出异常,无法执行

       after:最终通知(应用:清理现场)

              方法执行完毕后执行,无论方法中是否出现异常

环绕

try{

     //前置:before

    //手动执行目标方法

    //后置:afterRetruning

} catch(){

    //抛出异常 afterThrowing

} finally{

    //最终 after

}

四、  导入jar包

l  4个:

       aop联盟规范

       springaop 实现

       aspect规范

       springaspect 实现

五、  基于xml的实现

1.目标类:接口 + 实现

2.切面类:编写多个通知,采用aspectj 通知名称任意(方法名任意)

3.aop编程,将通知应用到目标类

4.测试

5.1   切面类

/**

 * 切面类,含有多个通知

 */

publicclass MyAspect {

   

    publicvoid myBefore(JoinPoint joinPoint){

        System.out.println("前置通知 " + joinPoint.getSignature().getName());

    }

   

    publicvoid myAfterReturning(JoinPoint joinPoint,Object ret){

        System.out.println("后置通知 " + joinPoint.getSignature().getName() + " , -->" + ret);

    }

   

    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{

        System.out.println("");

        //手动执行目标方法

        Object obj = joinPoint.proceed();

       

        System.out.println("");

        return obj;

    }

   

    publicvoid myAfterThrowing(JoinPoint joinPoint,Throwable e){

        System.out.println("抛出异常通知 " + e.getMessage());

    }

   

    publicvoid myAfter(JoinPoint joinPoint){

        System.out.println("最终通知");

    }

 

}

5.2   spring配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
     xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
               http://www.springframework.org/schema/beans/spring-beans.xsd
               http://www.springframework.org/schema/context 
               http://www.springframework.org/schema/context/spring-context.xsd
               http://www.springframework.org/schema/aop
                 http://www.springframework.org/schema/aop/spring-aop.xsd">


      <!-- 创建目标类 -->      
      <bean id="userService" class="com.nari.service.impl.UseServiceImpl"></bean>
        <!-- 创建切面类 --> 
      <bean id="myAspectBean" class="com.nari.c_springAop.MyAspectXml"></bean>
      
      <aop:config>
        <aop:aspect ref="myAspectBean">
          <aop:pointcut expression="execution(* com.nari.service.*impl.*.*(..))" id="myPointCut"/>
          <!-- 前置通知
              <aop:before method="myBefore" pointcut-ref="" pointcut=""/>
                  method:通知,及方法名
                  pointcut:切入点表达式 此表达式只能当前通知使用,这个不是必填项
                  pointcut-ref: 切入点引用,可以与其他通知共享切入点。
                                         通知方法里面的参数org.aspectj.lang.JoinPoint; 用来描述连接点(目标方法)
           -->
          <aop:before method="myBefore" pointcut-ref="myPointCut" />
          
          <!-- 后置通知,after-returning 目标方法正常执行后执行的 
             <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="obj"/>
             returning 通知方法的第二个参数名称
             public void myAfterReturning(JoinPoint joinPoint,Object obj)
                                          参数一:描述连接点
                                       参数二:类型必须是Object,参数名returning配置 为目标方法的放回值
             
             
          -->
          <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="obj"/>
          
          <!-- 环绕通知
          <aop:around method="myAround"  pointcut-ref="myPointCut"/>
          public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable
                            通知方法的放回类型必须是Object 
                           入参必须是 ProceedingJoinPoint类型的
                           必须抛出异常throws Throwable
          
           -->
           <aop:around method="myAround"  pointcut-ref="myPointCut"/>
           
           <!-- 抛出异常通知 
              <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
              throwing="e" 为通知方法的第二个参数的参数名称
              public void myAfterThrowing(JoinPoint joinPoint,Throwable e)
                                   参数二:为连接点的异常信息
           -->
           <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>
           
           <!-- 后置通知, 不管连接点是否出现异常都会执行的方法-->
           <aop:after method="myAfter" pointcut-ref="myPointCut"/>
        </aop:aspect>
      </aop:config>
     
</beans>

 六 基于注解的实现

6.1   替换bean

<!-- 1 创建目标类 -->

    <bean id="userServiceId" class="com.itheima.d_aspect.b_anno.UserServiceImpl"></bean>

    <!-- 2 创建切面类(通知) -->

    <bean id="myAspectId" class="com.itheima.d_aspect.b_anno.MyAspect"></bean>


l  注意:扫描

<beans xmlns="http://www.springframework.org/schema/beans"

       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                            http://www.springframework.org/schema/beans/spring-beans.xsd

                            http://www.springframework.org/schema/aop

                            http://www.springframework.org/schema/aop/spring-aop.xsd

                            http://www.springframework.org/schema/context

                            http://www.springframework.org/schema/context/spring-context.xsd">

<!-- 1.扫描注解类 -->

    <context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>

 <!-- 是AOP注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

6.2  替换aop

l  必须进行aspectj 自动代理

<!-- 2.确定 aop注解生效 -->

   <aop:aspectj-autoproxy></aop:aspectj-autoproxy>


l  声明切面

 <aop:aspect ref="myAspectId">


l  替换前置通知

<aop:before method="myBefore" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))"/>

   //切入点当前有效

   @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")

   publicvoid myBefore(JoinPoint joinPoint){

      System.out.println("前置通知 " + joinPoint.getSignature().getName());

   }

l  替换 公共切入点

<aop:pointcut expression="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" id="myPointCut"/>

//声明公共切入点

   @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")

   privatevoid myPointCut(){

   }

l  替换后置

<aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />

    @AfterReturning(value="myPointCut()" ,returning="ret")

    publicvoid myAfterReturning(JoinPoint joinPoint,Object ret){

        System.out.println("后置通知 " + joinPoint.getSignature().getName() + " , -->" + ret);

    }

l  替换环绕

<aop:around method="myAround" pointcut-ref="myPointCut"/>

@Around(value = "myPointCut()")

    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{

        System.out.println("");

        //手动执行目标方法

        Object obj = joinPoint.proceed();

       

        System.out.println("");

        return obj;

    }

l  替换抛出异常

<aop:after-throwing method="myAfterThrowing" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" throwing="e"/>

@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")

    publicvoid myAfterThrowing(JoinPoint joinPoint,Throwable e){

        System.out.println("抛出异常通知 " + e.getMessage());

    }

6.3   切面类

/**

 * 切面类,含有多个通知

 */

@Component

@Aspect

publicclass MyAspect {

   

    //切入点当前有效

//  @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")

    publicvoid myBefore(JoinPoint joinPoint){

        System.out.println("前置通知 " + joinPoint.getSignature().getName());

    }

   

    //声明公共切入点

    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")

    privatevoid myPointCut(){

    }

   

//  @AfterReturning(value="myPointCut()" ,returning="ret")

    publicvoid myAfterReturning(JoinPoint joinPoint,Object ret){

        System.out.println("后置通知 " + joinPoint.getSignature().getName() + " , -->" + ret);

    }

   

//  @Around(value = "myPointCut()")

    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{

        System.out.println("");

        //手动执行目标方法

        Object obj = joinPoint.proceed();

       

        System.out.println("");

        return obj;

    }

   

//  @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")

    publicvoid myAfterThrowing(JoinPoint joinPoint,Throwable e){

        System.out.println("抛出异常通知 " + e.getMessage());

    }

   

    @After("myPointCut()")

    publicvoid myAfter(JoinPoint joinPoint){

        System.out.println("最终通知");

    }

 

}

6.4   spring配置

<!-- 1.扫描注解类 -->

    <context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>

   

    <!-- 2.确定 aop注解生效 -->

    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

七  aop注解总结

@Aspect 声明切面,修饰切面类,从而获得 通知。

通知

       @Before前置

       @AfterReturning后置

       @Around环绕

       @AfterThrowing抛出异常

       @After最终

切入点

       @PointCut,修饰方法 privatevoid xxx(){} 一般为私有的没有返回值 之后通过“方法名”获得切入点引用








猜你喜欢

转载自blog.csdn.net/qq_36697880/article/details/80977851