动态代理和springAOP的介绍和使用

什么是aop

aop叫做面向切面编程,通过预编译方式和动态代理实现程序功能统一维护的技术。简单说,就是把程序中重复的部分拿出来,解耦提供可复用性,在需要执行的时候用动态代理技术,在不修改源码的基础上对方法进行增强。就是把重复的部分放在invoke方法中。

aop优势:减少重复代码,方便维护

aop相关术语解释,与配置无关哦~

(Pointcut)切入点:一个类中需要增加的方法才是切入点。
(Joinpoint)连接点:一个类中所有的方法都是连接点。
advice(通知):在method.invoke方法前的是前置通知,后的是后置通知,catch就是异常通知,finally就是最终通知,整个invoke方法就是环绕通知(在环绕通知中有明确的切入点方法(method.invoke)调用)。
Target(被代理对象):代理商代理的对象(工厂)
weaving(织入):就是在invoke中写增强功能点的过程。
proxy:代理对象
aspect(切面):切入点和通知的结合。配置那些方法需要在method.invoke之前执行,之后执行,最终执行。

什么是动态代理

就相当于你是买家,一开始你直接跟厂家进行购买产品,但现在出现了代理商,代理商从厂家购买产品,现在你只能从代理商哪里购买产品,代理商对厂家的产品进行了某些方面的改进和增强,这是一个动态过程,就是动态代理
特点:字节码文件使用的时候就会创建,就会加载。
作用:不修改源码的基础上,对方法增强
分类: 基于接口 基于子类

基于接口

package com.zxh.agent;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*

*  顾客——————代理商——————工厂。
* */
public class Customer {


    public static void main(String[] args) {
     final   Product pfactory  = new Productimpl(); //运行内部类访问外部属性,需要外部属性是final

    /*    动态代理:
        *   特点:字节码文件使用的时候就会创建,就会加载,不使用就不会加载创建,是动态的。
        *   作用:不修改源码的基础上,对方法增强
        分类: 基于接口  基于子类
        基于接口:
                    *   涉及的类(代理商):proxy
                *   提供者:JDK官方
        创建代理对象(生成代理商对象)
                   *        使用proxy类中的newProxyInstance方法
                创建代理对象的要求
                   *        代理对象至少要实现一个接口。(代理商至少要代理这个工厂的一个产品)
                   *  newProxyInstance的参数
                *                Classloader:
                *                           作用:会加载出代理对象的字节码(加载代理商的)
                *                                 但 里面写的是被代理对象(工厂){把工厂的类写进去加载,会返回一个代理商}
                   *             Class{}
                   *                        作用:让代理对象和被代理对象有相同的方法(把工厂的产品给代理商)
                   *             InvocationHandler
                   *                        作用:让代理对象在代理原来方法(产品)的基础上进行增强(增加一些新功能)。
                   *
                   * */
    //创建代理对象
        Product  p   =    (Product) Proxy.newProxyInstance(pfactory.getClass().getClassLoader(), pfactory.getClass().getInterfaces(),
                new InvocationHandler() {
                        /*
                        *  执行被代理对象(工厂)的任务接口方法,都会先经过这个方法才行。
                        * proxy:代理对象的引用
                        * method:当前执行的方法(产品)
                        * args:当前执行方法需要的参数
                        * return:和被代理对象方法(工厂的方法)有相同的返回值
                        * */
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object valuemethod = null;
                        //提供增强的方法(增加的新功能)
                        //新能能:顾客买到电脑后,有百分之20的钱属于代理商,剩下的才返回给被代理商
                        //1.获取方法需要的参数
                        Float price = (Float) args[0]; //因为SellProdeuct方法只有一个参数
                        //2.找出需要增强的方法
                        if ("SellProduct".equals(method.getName())) {
                            valuemethod = method.invoke(pfactory, price*0.8f);//返回被代理对象的方法和参数。
                        }
                        return  valuemethod;

                    }

                });
        p.SellProduct(10000f);

    }

}

使用AOP明确的事:

1.首先要写好业务层代码
2.然后把公用代码抽取出来,制作成通知。(开发最后阶段做)
3.配置切入点和通知的关系,搞出切面。

运行过程:
1.首先spring框架会监测切入点方法,
2.发现要运行切入点方法之后,就会创建代理对象,
3.然后根据配置的通知类型,将通知织入到相应位置
4.从上往下执行整个代码

springAOP基于XML的配置

首先假定一个日志类当作通知类

package com.zxh.utils;

import org.aspectj.lang.ProceedingJoinPoint;

/*
* 记录日志工具类,提供公共代码
* */
public class Logger {
/*
* 用于打印日记,在切入点方法执行之前执行(前置通知),
* */

    //前置通知
    public void Beforeprintlog()
    {
        System.out.println("前置通知Logger中的printlog开始执行");
    }
    //后置通知
    public void AfterPrintlog()
    {
        System.out.println("后置通知Logger中的printlog开始执行");
    }
    //异常通知
    public void ThrowPrintlog()
    {
        System.out.println("异常异常Logger中的printlog开始执行");
    }
    //最终通知
    public void FinallPrintlog()
    {
        System.out.println("最终通知Logger中的printlog开始执行");
    }
    /*
    * 环绕通知
    * :配置环绕通知,需要调用ProceedingJoinPoint类中的proceed方法才能实现切入点的使用
    *
    *  rtvalue = pjp.proceed(args);
    * 在这个方法前的就是前置通知,
    * 在后的就是后置通知,
    * 在异常中就是异常通知,
    * 在finally中就是最终通知
    * */
    public  Object AroundPrintlog(ProceedingJoinPoint pjp)
    {
        try {
             Object rtvalue=null;
              Object[] args = pjp.getArgs();
            System.out.println("环绕通知中的前置通知");
            rtvalue = pjp.proceed(args);
            System.out.println("环绕通知中的后置通知");
            return  rtvalue;
        } catch (Throwable throwable) {
            System.out.println("环绕通知中的异常通知");
           throw  new RuntimeException(throwable);
        }
        finally {
            System.out.println("环绕通知中的最终通知");

        }

    }
}

然后就是在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"
       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 ">

    <!-- bean definition & AOP specific configuration -->

    <!--配置springIOC,把service对象配置进来-->
    <bean id="accountservice" class="com.zxh.serviceimpl.AccountServiceimpl"></bean>

    <!--springAOP配置步骤
        1.把通知bean交给spring管理
        2.使用aop:cofig标志开始AOP的配置
        3.使用aop:aspect标签开始配置切面(key-value)表示当前类是一个切面类
                        属性: id :给切面提供一个key
                               ref:指定通知类bean的id
        4.在aop:aspect内部使用对应的标志来配置通知的类型:
          aop:pointcut 声明切入点方法
          	属性:
                      id:用于指定切入点表达式的名称
                     pointcut:用于指定切入点(切入方法)表达式,含义是指定对业务层中那些方法增强。
                    前置通知:aop:before
                                属性 method:用于指定类中,哪一个方法是前置通知。
                                属性:pointcut-ref:指定引用的切入点表达式 ID。
                                属性:pointcut:用于指定切入点(切入方法)表达式,含义是指定对业务层中那些方法增强。
                                表达式写法:

                                        关键字:execution(表达式)
                                        (单个)表达式: 访问求修饰符 返回值 包名.包名....类名.方法名
                                                        public void com.zxh.serviceimpl.AccountServiceimpl.SaveAccount()
                                                访问修饰符可以省略
                                                 void com.zxh.serviceimpl.AccountServiceimpl.SaveAccount()
                                                 返回值可以使用通配符
                                                  * com.zxh.serviceimpl.AccountServiceimpl.SaveAccount()
                                                  包名可以使用通配符标识任意包,但有几级包,就需要写几个*.
                                                  * *.*.*.AccountServiceimpl.SaveAccount()
                                                  包名也可以使用..表示当前包及其子包
                                                  * *..AccountServiceimpl.SaveAccount()
                                                  类名和方法名都可以使用* 进行通配
                                                  * *..*.*()
                                                  参数列表
                                                    可以直接写数据类型
                                                        基本类型直接写名称 int long flaot double boolean
                                                        引用类型写包名.类名 java.lang.String
                                                    可以使用通配 * 表示任意参数
                                                        * *..*.*(*)
                                                    也可以使用..表示有无参数都可以。
                                                    * *..*.*(..)
                                        全通配:* *..*.*(..)

                               切入点表达式实际开发写法,要写到业务层实现类中所有的方法
                                       * com.zxh.serviceimpl.*.*(..)

                    后置通知:aop:after-returning
                    异常通知: aop:after-throwing
                    最终通知:aop:after
                    环线通知:aop:around


    -->
    <bean id="logger" class="com.zxh.utils.Logger"></bean>

    <!-- 配置AOP-->
    <aop:config>
        <aop:pointcut id="adviceaccount" expression="execution( * com.zxh.serviceimpl.*.*(..))"/>
        <!-- 配置切面-->
        <aop:aspect id="logbeforeadvice" ref="logger">
            <!--配置通知类型,且将通知方法和切入点方法结合起来-->
            <!--前置通知-->
            <aop:before method="Beforeprintlog" pointcut-ref="adviceaccount" ></aop:before>
            <!--后置通知-->
            <aop:after-returning method="AfterPrintlog" pointcut-ref="adviceaccount"></aop:after-returning>
            <!--异常通知-->
            <aop:after-throwing method="ThrowPrintlog" pointcut-ref="adviceaccount"></aop:after-throwing>
            <!--最终通知-->
            <aop:after method="FinallPrintlog" pointcut="execution(* com.zxh.serviceimpl.*.*(..))"></aop:after>
            <!--环绕通知-->
            <!--配置环绕通知,
                环绕通知就是在方法中通过编码方式来执行 前置,后置,异常,最终等通知。-->
            <aop:around method="AroundPrintlog" pointcut-ref="adviceaccount"></aop:around>
        </aop:aspect>
    </aop:config>
</beans>

springaop注解配置的步骤

<?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">

    <!--步骤
            1.配置创建容器时需要扫描的包 - - -context.component

            2.配置AOP的注解支持 - - - aop:asepectj-autoproxy
                  或者再切面类中加入@EnableAspectJAutoProxy标签
            3.把相关的类注入的AOP容器中 @component
            4.声明切面类   - - -  @Aepect
            5.在切面类中声明切入点  @Pointcut
            6.在切入类中声明通知 @Before @After ....
            7.将切入点和通知结合起来形成切面
    -->


    <!-- 配置spring创建容器时需要扫描的包-->
         <context:component-scan base-package="com.zxh" ></context:component-scan>
    <!--配置spring开启支持注解的AOP支持 -->
<!--        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>-->

</beans>

切面类的相关配置

package com.zxh.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

/*
* 记录日志工具类,提供公共代码
* */
@Component(value = "logger")
@EnableAspectJAutoProxy
@Aspect()//表示当前类是一个切面类 相当于<aop:aspect></asp:aspect>标签一样
public class Logger {

    @Pointcut(value = "execution(* com.zxh.serviceimpl.*.*(..))")//声明serviceiimpl中那些方法是切入点
    public void servicePointcut(){}

    //前置通知
    @Before("servicePointcut()")//将切入点和通知联系起来形成切面。
    public void Beforeprintlog()
    {
        System.out.println("前置通知Logger中的printlog开始执行");
    }
    //后置通知
    @AfterReturning("servicePointcut()")
    public void AfterPrintlog()
    {
        System.out.println("后置通知Logger中的printlog开始执行");
    }
    //异常通知
    @AfterThrowing("servicePointcut()")
    public void ThrowPrintlog()
    {
        System.out.println("异常异常Logger中的printlog开始执行");
    }
    //最终通知
    @After("servicePointcut()")
    public void FinallPrintlog()
    {
        System.out.println("最终通知Logger中的printlog开始执行");
    }
    /*
    * 环绕通知
    * :配置环绕通知,需要调用ProceedingJoinPoint类中的proceed方法才能实现切入点的使用
    *
    *  rtvalue = pjp.proceed(args);
    * 在这个方法前的就是前置通知,
    * 在后的就是后置通知,
    * 在异常中就是异常通知,
    * 在finally中就是最终通知
    * */
    //@Around("servicePointcut()")
    public  Object AroundPrintlog(ProceedingJoinPoint pjp)
    {
        try {
             Object rtvalue=null;
              Object[] args = pjp.getArgs();
            System.out.println("环绕通知中的前置通知");
            rtvalue = pjp.proceed(args);
            System.out.println("环绕通知中的后置通知");
            return  rtvalue;
        } catch (Throwable throwable) {
            System.out.println("环绕通知中的异常通知");
           throw  new RuntimeException(throwable);
        }
        finally {
            System.out.println("环绕通知中的最终通知");

        }

    }
}

spring声明式事务管理
就是spring通过xml配置,声明dao层中的方法执行时,需要进行的事务控制(提交,回滚)。
spring编程式事务管理
就是spring通过方法调用,来告诉执行dao层中那些方法需要事务控制。

总结

学习springAOP首先要明白什么是AOP,AOP有什么作用,然后再去了解什么是动态代理,接下里就是AOP XML配置的使用和属性和注解配置的使用和属性。

发布了5 篇原创文章 · 获赞 2 · 访问量 338

猜你喜欢

转载自blog.csdn.net/weixin_43881925/article/details/104571838