SpringAOP和AspectJ详解

来源:互联网 发布:mac上常用的软件 编辑:程序博客网 时间:2024/06/08 13:50

一、AOP

@作者:温涛@时间:2017-9-21

1.1 AOP简介

a、面向切面编程(Aspect Oriented Programming):    通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。b、AOP 是一个概念,并没有设定具体语言的实现,它能克服那些只有单继承特性语言的缺点,spring2.0 之后整合 AspectJ 第三方 AOP 技术。c、AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码。d、AspectJ 是一个面向切面的框架,它扩展了 Java 语言。AspectJ 定义了 AOP 语法所以它有一个专门的编译器用来生成遵守 Java 字节编码规范的 Class 文件。e、经典应用:事务管理、性能监视、安全检查、缓存 、日志等

1.2 AOP 与 与 OOP 区别

OOP(面向对象编程):针对业务处理过程的实体及其属性和行为进行抽象封装,以获得更加清晰高效的逻辑单元划分。AOP: 则是针对业务处理过程中的切面进行提取,它所面对的是处理过程中的某个步骤或阶段,以获得逻辑过程中各部分之间低耦合性的隔离效果。这两种设计思想在目标上有着本质的差异。换而言之,OOD/OOP 面向名词领域,AOP 面向动词领域。

1.3 AOP实现原理

静态 AOP:将切面代码直接编译到 Java 类文件中。动态 AOP:是指将切面代码进行动态织入实现的 AOP。aop底层将采用代理机制进行实现:    1.接口 + 实现类 :spring采用 jdk 的动态代理Proxy。    2.实现类:spring 采用 cglib字节码增强。

1.4 AOP术语

1.target:目标类,需要被代理的类。例如:UserService2.Joinpoint(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法3.PointCut 切入点:已经被增强的连接点。例如:addUser()4.advice 通知/增强,增强代码。例如:after、before5.Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.6.proxy 代理类7.Aspect(切面): 是切入点pointcut和通知advice的结合    一个线是一个特殊的面。    一个切入点和一个通知,组成成一个特殊的面。

1.5 Proxy动态代理工厂

public class MyProxy {    public static BookService createProxy(){            //目标类        final BookService bookService = new BookServiceImpl();        //切面类        final MyAspcet1 myAspect = new MyAspcet1();        //代理类        BookService bookProxy =(BookService)Proxy.newProxyInstance(                MyProxy.class.getClassLoader(),                bookService.getClass().getInterfaces(),                new InvocationHandler() {        public Object invoke(Object proxy, Method method, Object[] args)                            throws Throwable {                        myAspect.before();                        Object invoke = method.invoke(bookService, args);                        myAspect.after();                        return invoke;                    }                });        return bookProxy;    }}解析:    代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面     *  Proxy.newProxyInstance     *      参数1:loader ,类加载器,动态代理类     *          运行时创建,任何类都需要类加载器将其加载到内存。     *          一般情况:     *                  当前类.class.getClassLoader();     *              目标类实例.getClass().get...     *      参数2:Class[] interfaces 代理类需要实现的所有接口     *          方式1:目标类实例.getClass().getInterfaces();     *          注意:只能获得自己接口,不能获得父元素接口     *          方式2:new Class[]{UserService.class}        *          例如:jdbc 驱动  --> DriverManager  获得接口 Connection     *      参数3:InvocationHandler 处理类,接口,必须进行实现类,一般采用匿名内部类     *          提供 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke     *              参数31:Object proxy :代理对象     *              参数32:Method method : 代理对象当前执行的方法的描述对象(反射)     *                  执行方法名:method.getName()     *                  执行方法:method.invoke(对象,实际参数)     *              参数33:Object[] args :方法实际参数

1.6 cglib动态代理工厂

public class MyProxy {    public static BookService createCglib(){        //目标类        final BookServiceImpl bookServiceImpl = new BookServiceImpl();        //增强类        final MyAspcet1 myAspcet = new MyAspcet1();        //代理类 ,采用cglib,底层创建目标类的子类        //核心类        Enhancer enhancer = new Enhancer();        //确定父类        enhancer.setSuperclass(bookServiceImpl.getClass());        //设置回调函数 , MethodInterceptor接口 等效 jdk InvocationHandler接口        //intercept() 等效 jdk  invoke()        //  参数1、参数2、参数3:跟invoke一样        //  参数4:methodProxy 方法的代理        enhancer.setCallback(new MethodInterceptor() {            public Object intercept(Object proxy, Method method, Object[] args,                    MethodProxy arg3) throws Throwable {                myAspcet.before();                //执行目标类                Object invoke = method.invoke(bookServiceImpl, args);                //执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)                methodProxy.invokeSuper(proxy, args);                myAspcet.after();                return invoke;            }        });        //创建代理        BookServiceImpl create = (BookServiceImpl)enhancer.create();        return create;    }}

1.7 spring 采用的动态机制

如果目标对象,有接口,优先使用 jdk 动态代理(接口+实现类)。如果目标对象,无接口,使用 cglib 动态代理(实现类)。但是,可通过配置,让spring总是使用cglib 动态代理。关系:    proxy动态代理是父子关系    cglib动态代理是兄弟关系

1.8 AOP联盟通知类型

AOP联盟为通知Advice定义了org.aopalliance.aop.AdviceSpring按照通知Advice在目标类方法的连接点位置,可以分为5类:•   前置通知 org.springframework.aop.MethodBeforeAdvice•   在目标方法执行前实施增强•   后置通知 org.springframework.aop.AfterReturningAdvice•   在目标方法执行后实施增强•   环绕通知 org.aopalliance.intercept.MethodInterceptor•   在目标方法执行前后实施增强•   异常抛出通知 org.springframework.aop.ThrowsAdvice•   在方法抛出异常后实施增强•   引介通知 org.springframework.aop.IntroductionInterceptor•   在目标类中添加一些新的方法和属性用法:增强类实现对应的接口。

1.9 spring AOP全自动编程配置(了解,一般配合AspectJ框架使用)

<?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"       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">    <!-- 1 创建目标类 -->    <bean id="userService" class="com.itheima.c_spring_aop.UserServiceImpl"></bean>    <!-- 2 创建切面类(通知,切面类实现MethodInterceptor) -->    <bean id="myAspect" class="com.itheima.c_spring_aop.MyAspect"></bean>    <!-- 3 aop编程         3.1 导入命名空间        3.2 使用 <aop:config>进行配置                proxy-target-class="true" 声明时使用cglib代理            <aop:pointcut> 切入点 ,从目标对象获得具体方法            <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点                advice-ref 通知引用                pointcut-ref 公共切入点引用                pointcut 自己的切入点表达式        3.3 切入点表达式            execution(* com.itheima.c_spring_aop.*.*(..))            选择方法:返回值任意   包   类名任意   方法名任意   参数任意    -->    <aop:config proxy-target-class="true">        <aop:pointcut expression="execution(* com.itheima.c_spring_aop.*.*(..))" id="myPointCut"/>        <aop:advisor advice-ref="myAspect" pointcut-ref="myPointCut"/>    </aop:config></beans>

二、AspectJ

2.1 简介

a、AspectJ是一个基于Java语言的AOP框架b、Spring2.0以后新增了对AspectJ切点表达式支持c、@AspectJ 是AspectJ1.5新增功能,通过JDK5注解技术,允许直接在Bean类中定义切面d、新版本Spring框架,建议使用AspectJ方式来开发AOPe、主要用途:自定义开发

2.2 切入点表达式

1.execution()  用于描述方法 【掌握】语法:execution(修饰符  返回值  包.类.方法名(参数) throws异常)    修饰符,一般省略        public      公共方法        *       任意    返回值,不能省略        void        返回没有值        String      返回值字符串            *       任意    包,[省略]        com.wentao.crm          固定包        com.wentao.crm.*.service    crm包下面子包任意 (例如:com.wentao.crm.staff.service)        com.wentao.crm..        crm包下面的所有子包(含自己)        com.wentao.crm.*.service..  crm包下面任意子包,固定目录service,service目录任意包    类,[省略]        UserServiceImpl         指定类            *Impl               以Impl结尾            User*               以User开头                *               任意    方法名,不能省略        addUser             固定方法        add*                以add开头            *Do             以Do结尾            *               任意    (参数)        ()              无参        (int)           一个整型    (int ,int)          两个        (..)            参数任意    throws ,可省略,一般不写。综合1    execution(* com.wentao.crm.*.service..*.*(..))综合2    <aop:pointcut expression="execution(* com.wentao.*WithCommit.*(..)) ||                           execution(* com.wentao.*Service.*(..))" id="myPointCut"/>

2.3 AspectJ 通知类型

区别:    aop联盟定义通知类型,具有特性接口,必须实现,从而确定方法名称。    aspectj 通知类型,只定义类型名称。已经方法格式。个数:6种,知道5种,掌握1中。before:前置通知(应用:各种校验)    在方法执行前执行,如果通知抛出异常,阻止方法运行afterReturning:后置通知(应用:常规数据处理)    方法正常返回后执行,如果方法中抛出异常,通知无法执行    必须在方法执行后才执行,所以可以获得方法的返回值。around:环绕通知(应用:十分强大,可以做任何事情)    方法执行前后分别执行,可以阻止方法的执行    必须手动执行目标方法afterThrowing:抛出异常通知(应用:包装异常信息)    方法抛出异常后执行,如果方法没有抛出异常,无法执行after:最终通知(应用:清理现场)    方法执行完毕后执行,无论方法中是否出现异常

2.4 AspectJ 基于xml

步骤:1.目标类:接口 + 实现2.切面类:编写多个通知,采用aspectj 通知名称任意(方法名任意)3.aop编程,将通知应用到目标类

2.4.1 切面类写法

public class MyAspect {    public void myBefore(JoinPoint joinPoint){        System.out.println("前置通知 : " + joinPoint.getSignature().getName());    }    public void 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;    }    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){        System.out.println("抛出异常通知 : " + e.getMessage());    }    public void myAfter(JoinPoint joinPoint){        System.out.println("最终通知");    }}

2.4.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: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 创建目标类 -->        <bean id="userService" class="com.wentao.service.UserServiceImpl"></bean>        <!-- 2 创建切面类(通知) -->        <bean id="myAspect" class="com.wentao.utils.MyAspect"></bean>        <!-- 3 aop编程             <aop:aspect> 将切面类 声明“切面”,从而获得通知(方法)                ref 切面类引用            <aop:pointcut> 声明一个切入点,所有的通知都可以使用。(一定别忘了)                expression 切入点表达式                id 名称,用于其它通知引用        -->        <aop:config>            <aop:aspect ref="myAspect">                <!-- 切入点别忘记配置 -->                <aop:pointcut expression="execution(* com.wentao.service.UserServiceImpl.*(..))" id="myPointCut"/>                <!-- 3.1 前置通知                     <aop:before method="" pointcut="" pointcut-ref=""/>                        method : 通知,及方法名                        pointcut :切入点表达式,此表达式只能当前通知使用。                        pointcut-ref : 切入点引用,可以与其他通知共享切入点。                    通知方法格式:public void myBefore(JoinPoint joinPoint){                        参数1:org.aspectj.lang.JoinPoint  用于描述连接点(目标方法),获得目标方法名等                    例如:                    <aop:before method="myBefore" pointcut-ref="myPointCut"/>                -->                <!-- 3.2后置通知  ,目标方法后执行,获得返回值                    <aop:after-returning method="" pointcut-ref="" returning=""/>                        returning 通知方法第二个参数的名称                    通知方法格式:public void myAfterReturning(JoinPoint joinPoint,Object ret){                        参数1:连接点描述                        参数2:类型Object,参数名 returning="ret" 配置的                    例如:                    <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret" />                -->                <!-- 3.3 环绕通知 *****                    <aop:around method="" pointcut-ref=""/>                    通知方法格式:public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{                        返回值类型:必须是Object                        方法名:任意                        参数:必须是org.aspectj.lang.ProceedingJoinPoint                        抛出异常                    执行目标方法:Object obj = joinPoint.proceed();                    例如:                    <aop:around method="myAround" pointcut-ref="myPointCut"/>                -->                <!-- 3.4 抛出异常                    <aop:after-throwing method="" pointcut-ref="" throwing=""/>                        throwing :通知方法的第二个参数名称                    通知方法格式:public void myAfterThrowing(JoinPoint joinPoint,Throwable e){                        参数1:连接点描述对象                        参数2:获得异常信息,类型Throwable ,参数名由throwing="e" 配置                    例如:                    <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/>                -->                <!-- 3.5 最终通知 -->                           <aop:after method="myAfter" pointcut-ref="myPointCut"/>            </aop:aspect>        </aop:config>    </beans>

2.5 AspectJ基于注解

2.5.1 注解用法

1.切面类    @Aspect  声明切面,修饰切面类,从而获得 通知。2.公共切入点(修饰方法 private void xxx(){} 之后通过“方法名”获得切入点引用)    //声明公共切入点    @Pointcut("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")    private void myPointCut(){    }3.通知    @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")    @AfterReturning(value="myPointCut()" ,returning="ret")    @Around(value = "myPointCut()")    @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")    @After("myPointCut()")

2.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: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.wentao.aspectj"></context:component-scan>        <!-- 2.确定 aop注解生效 -->        <aop:aspectj-autoproxy></aop:aspectj-autoproxy></beans>
原创粉丝点击