• SpringAOP-基于@AspectJ的简单入门


    一、AOP的基本概念:

    •  连接点(Jointpoint):表示需要在程序中插入横切关注点的扩展点,连接点可能是类初始化、方法执行、方法调用、字段调用或处理异常等等,Spring只支持方法执行连接点,在AOP中表示为“在哪里干”;
    • 切入点(Pointcut):选择一组相关连接点的模式,即可以认为连接点的集合,Spring支持perl5正则表达式和AspectJ切入点模式,Spring默认使用AspectJ语法,在AOP中表示为“在哪里干的集合”;
    • 通知(Advice):在连接点上执行的行为,通知提供了在AOP中需要在切入点所选择的连接点处进行扩展现有行为的手段;包括前置通知(before advice)、后置通知(after advice)、环绕通知(around advice),在Spring中通过代理模式实现AOP,并通过拦截器模式以环绕连接点的拦截器链织入通知;在AOP中表示为“干什么”;
      • 前置通知(Before Advice):在切入点选择的连接点处的方法之前执行的通知,该通知不影响正常程序执行流程(除非该通知抛出异常,该异常将中断当前方法链的执行而返回);
      • 环绕通知(Around Advices):环绕着在切入点选择的连接点处的方法所执行的通知,环绕通知可以在方法调用之前和之后自定义任何行为,并且可以决定是否执行连接点处的方法、替换返回值、抛出异常等等。
      • 后置通知(After Advice):在切入点选择的连接点处的方法之后执行的通知,包括如下类型的后置通知:
        • 后置返回通知(After returning Advice):在切入点选择的连接点处的方法正常执行完毕时执行的通知,必须是连接点处的方法没抛出任何异常正常返回时才调用后置通知。
        • 后置异常通知(After throwing Advice): 在切入点选择的连接点处的方法抛出异常返回时执行的通知,必须是连接点处的方法抛出任何异常返回时才调用异常通知。
        • 后置最终通知(After finally Advice): 在切入点选择的连接点处的方法返回时执行的通知,不管抛没抛出异常都执行,类似于Java中的finally块。
    • 方面/切面(Aspect):横切关注点的模块化,比如上边提到的日志组件。可以认为是通知、引入和切入点的组合;在Spring中可以使用Schema和@AspectJ方式进行组织实现;在AOP中表示为“在哪干和干什么集合”;
    • 引入(inter-type declaration):也称为内部类型声明,为已有的类添加额外新的字段或方法,Spring允许引入新的接口(必须对应一个实现)到所有被代理对象(目标对象), 在AOP中表示为“干什么(引入什么)”;
    • 目标对象(Target Object):需要被织入横切关注点的对象,即该对象是切入点选择的对象,需要被通知的对象,从而也可称为“被通知对象”;由于Spring AOP 通过代理模式实现,从而这个对象永远是被代理对象,在AOP中表示为“对谁干”;
    • AOP代理(AOP Proxy):AOP框架使用代理模式创建的对象,从而实现在连接点处插入通知(即应用切面),就是通过代理来对目标对象应用切面。在Spring中,AOP代理可以用JDK动态代理或CGLIB代理实现,而通过拦截器模型应用切面。
    • 织入(Weaving):织入是一个过程,是将切面应用到目标对象从而创建出AOP代理对象的过程,织入可以在编译期、类装载期、运行期进行。

    注解形式:

    步骤一、定义一个interface

    public interface ArithmeticCalculator {
        double plus(int i, int j);
        double sub(int i, int j);
        double multi(int i, int j);
        double div(int i, int j);
    }

    步骤二、实现上面的接口

    import org.springframework.stereotype.Component;
    
    @Component("arithmeticCalculator")
    public class ArithmeticCalculatorImpl implements ArithmeticCalculator {
    
        public double plus(int i, int j) {
            double result = i + j;
            return result;
        }
    
        public double sub(int i, int j) {
            double result = i - j;
            return  result;
        }
    
        public double multi(int i, int j) {
            double result = i * j;
            return result;
    
        }
    
        public double div(int i, int j) {
            double result = i / j;
            return result;
    
        }
    }

    步骤三、写切面类

    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    
    @Aspect
    @Component
    public class LoggingAspect {
        /**
         * 定义一个方法, 用于声明切入点表达式. 一般地, 
         *该方法中再不需要添入其他的代码.
         * 使用 @Pointcut 来声明切入点表达式.
         * 后面的其他通知直接使用方法名来引用当前的切入点表达式.
         */
        @Pointcut("execution(* com.spring2.lee.aop.impl.*.*(..))")
        public void declareJointPointExpression(){}
    
        /**
         * 前置通知
         * 在 com.atguigu.spring.aop.ArithmeticCalculator
         * 接口的每一个实现类的每一个方法开始之前执行一段代码
         * 用通配符*来表示所有
         */
    //    @Before("execution(public double com.spring2.lee.aop.impl.ArithmeticCalculator.plus(int, int))")
        @Before("declareJointPointExpression()")
        public void beforeMethod(JoinPoint joinPoint) {
            String methodName = joinPoint.getSignature().getName();
            Object[] args = joinPoint.getArgs();
            System.out.println("before method " + methodName + " begin with:" + Arrays.asList(args));
        }
    
        /**
         * 后置通知
         * 在方法执行之后执行的代码. 无论该方法是否出现异常
         * @param joinPoint
         */
    
        @After("execution(public double com.spring2.lee.aop.impl.*.*(..))")
        public void afterMethod(JoinPoint joinPoint) {
            String methodName = joinPoint.getSignature().getName();
            Object[] args = joinPoint.getArgs();
            System.out.println("after method " + methodName + 
                           " end " + Arrays.asList(args));
        }
    
        /**
         * 返回通知
         * 在方法法正常结束受执行的代码
         * 返回通知是可以访问到方法的返回值的!
         */
        @AfterReturning(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))",
                returning = "result")
        public void afterReturning(JoinPoint joinPoint, 
           Object result) {
            String methodName = joinPoint.getSignature().getName();
            System.out.println("The method " + methodName + 
               " ends with " + result);
        }
    
        /**
         * 异常通知
         * 在目标方法出现异常时会执行的代码.
         * 可以访问到异常对象; 且可以指定在出现特定异常时在执行通知代码
         */
        @AfterThrowing(value = "execution(public double com.spring2.lee.aop.impl.*.*(..))", throwing = "e")
        public void afterThrowing(JoinPoint joinPoint, Exception e) {
            String methodName = joinPoint.getSignature().getName();
            System.out.println("The method " + methodName + 
            " occurs excetion:" + e);
        }
    
        /**
         * 环绕通知需要携带 ProceedingJoinPoint 类型的参数.
         * 环绕通知类似于动态代理的全过程: ProceedingJoinPoint 类型的参数可以决定是否执行目标方法.
         * 且环绕通知必须有返回值, 返回值即为目标方法的返回值
         */
        @Around("execution(public double com.spring2.lee.aop.impl.*.*(..))")
        public Object aroundMethod(ProceedingJoinPoint pjd) {
    
            Object result = null;
            String methodName = pjd.getSignature().getName();
    
            try {
                //前置通知
                System.out.println("The method " + methodName + " begins with " + Arrays.asList(pjd.getArgs()));
                //执行目标方法
                result = pjd.proceed();
                //返回通知
                System.out.println("The method " + methodName + " ends with " + result);
            } catch (Throwable e) {
                //异常通知
                System.out.println("The method " + methodName + " occurs exception:" + e);
                throw new RuntimeException(e);
            }
            //后置通知
            System.out.println("The method " + methodName + " ends");
    
            return result;
        }
    
    }

    步骤四、Spring的配置文件中使用aop命名空间

    <?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: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-3.0.xsd
                http://www.springframework.org/schema/aop
                http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                http://www.springframework.org/schema/context
                http://www.springframework.org/schema/context/spring-context-3.0.xsd
           default-autowire="byName" default-lazy-init="false">
        <!--
            自动为Spring容器中那些匹配@AspectJ切面的Bean创建代理,完成切面织入。
            proxy-target-class属性,默认是false,表示使用JDK动态代理技术织入增强。
            当设置为true时,表示使用CGLib动态代理技术织入增强。不过即使设置为false,
            如果目标类没有实现接口,则Spring将自动使用CGLib动态代理
        -->
        <aop:aspectj-autoproxy proxy-target-class="false"/>
    </beans>

    步骤五、测试

    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MainTest {
        public static void main(String[] args) {
            //1.创建Spring 的IOC 容器
            ApplicationContext application = new ClassPathXmlApplicationContext("applicationContext.xml");
            //2. 从IOC 容器中获取bean 的实例
            ArithmeticCalculator arithmeticCalculator = application.getBean(ArithmeticCalculator.class);
            double result = arithmeticCalculator.div(2,2);
            //System.out.println("result:" + result);
        }
    }

    二、用xml配置的方式实现AOP

    Java代码跟上面的一样,只不过注解都没有了,都是用xml来配置bean,所以只粘贴xml

    <?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: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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
           <!-- 配置 bean -->
           <bean id="arithmeticCalculator"
                 class="com.spring2.lee.aop.impl.ArithmeticCalculatorImpl"></bean>
           <!-- 配置切面的 bean. -->
           <bean id="loggingAspect"
                 class="com.spring2.lee.aop.impl.LoggingAspect"></bean>
           <bean id="vlidationAspect"
                 class="com.spring2.lee.aop.impl.VlidationAspect"></bean>
           <!-- 配置 AOP -->
           <aop:config>
                  <!-- 配置切点表达式 -->
                  <aop:pointcut id="pointcut" expression="execution(* com.spring2.lee.aop.impl.ArithmeticCalculator.*(int, int))"/>
                  <!-- 配置切面及通知 -->
                  <aop:aspect ref="loggingAspect" order="2">
                         <aop:before method="beforeMethod" pointcut-ref="pointcut"/>
                         <aop:after method="afterMethod" pointcut-ref="pointcut"/>
                         <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="e"/>
                         <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
                         <!--
                             <aop:around method="aroundMethod" pointcut-ref="pointcut"/>
                       -->
                  </aop:aspect>
                  <aop:aspect ref="vlidationAspect" order="1">
                         <aop:before method="validateArgs" pointcut-ref="pointcut"/>
                  </aop:aspect>
           </aop:config>
           
    
    </beans>
  • 相关阅读:
    JavaScript闭包
    模块模式——方法
    产品与技术
    读书笔记
    屌丝求职记
    正则表达式regex狂记
    css狂记
    html狂记
    Android狂记忆
    关于调式
  • 原文地址:https://www.cnblogs.com/happyflyingpig/p/8023148.html
Copyright © 2020-2023  润新知