zoukankan      html  css  js  c++  java
  • Spring笔记3

    动态代理**

    特点:字节码随用随创建,随用随加载

    作用:不修改源码的基础上对方法增强

    分类:

    ​ 基于接口的动态代理

    ​ 基于子类的动态代理

    基于接口的动态代理:

    涉及的类:Proxy

    如何创建代理对象:

    ​ 使用Proxy类中的newProxyInstance方法

    创建代理对象的要求:被代理的类最少实现一个接口,如果没有则不能使用

    newProxyInstance方法的参数:

    ClassLoader :类加载器,他是用于加载代理对象字节码的,和被代理使用相同的类加载器

    Class[] :字节码数组:他是用于让代理对象和被代理对象有相同方法

    InvocationHandler:用于提供增强的代码,他是让我们写如何代理,一般都是些一个该接口的实现类,通常情况下都是匿名内部类

    package com.itheima;
    
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class Client {
        public static void main(String[] args) {
            final Producer producer = new Producer();
            producer.saleProduct(10000f);
    
           Iproducer proxyProducer = (Iproducer)Proxy.newProxyInstance(producer.getClass().getClassLoader(),
                    producer.getClass().getInterfaces(),
                    new InvocationHandler() {
                        //该方法的作用,具有拦截功能
                        //执行被代理对象的任何接口方法都会经过该方法
                        //proxy:代理对象的引用
                        //Method:当前执行的方法
                        //args:当前执行方法所需的参数
                        //return:和被代理对象方法有相同的返回值
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            //提供增强的代码
                            Object returnValue = null;
                            //获取方法执行的参数
                            Float money = (Float)args[0];
                            //判断当前方法
                            if("saleProduct".equals(method.getName())){
                            returnValue =  method.invoke(producer,money*0.8f);
                        }
                        return returnValue;
                        }
                    });
            proxyProducer.saleProduct(10000f);
        }
    }
    
    

    基于子类的动态代理

    需要导入cglib包

    涉及的类:Enhancer

    如何创建代理对象:使用Enhancer类中的create方法

    创建代理对象的要求:被代理类不能是最终类

    create方法的参数

    Class:字节码,用于指定被代理对象的字节码

    Callback:用于提供增强的代码,一般写的都是该接口的子接口实现类,MethodInterceptor

    package com.itheima.cglib;
    
    
    import com.itheima.Iproducer;
    import net.sf.cglib.proxy.Enhancer;
    import net.sf.cglib.proxy.MethodInterceptor;
    import net.sf.cglib.proxy.MethodProxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    public class Client {
        public static void main(String[] args) {
            final Producer producer = new Producer();
            producer.saleProduct(10000f);
    
    
           Producer cglibProducer = (Producer) Enhancer.create(producer.getClass(), new MethodInterceptor() {
    
                public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                    //提供增强的代码
                    Object returnValue = null;
                    //获取方法执行的参数
                    Float money = (Float)objects[0];
                    //判断当前方法
                    if("saleProduct".equals(method.getName())){
                        returnValue =  method.invoke(producer,money*0.8f);
                    }
                    return returnValue;
                }
            });
           cglibProducer.saleProduct(10000f);
        }
    }
    
    

    AOP:全称是Aspect Oriented Programming 面向切面编程

    把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强

    AOP相关术语

    Joinpoint(连接点):所谓连接点是值那些被拦截到的点,在spring中,这些点指的是方法,因为spring只支持方法类型的连接点

    pointcut(切入点):所谓切入点是指我们要对哪些JoinPoint进行拦截的定义(被增强的方法才是切入点)

    Advice(通知/增强):所谓的通过指的是拦截到Joinpoint之后所要做的事情就是通知,通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知

    Target(目标对象):代理的目标对象

    Weaving(织入):指的是把增强应用到目标对象来创建新的代理对象的过程

    Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类

    Aspect(切面):是切入和通知的结合

    spring基于XML的AOP

    1.导入两个坐标

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.itheima</groupId>
        <artifactId>day03_eesy_03springAOP</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <packaging>jar</packaging>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>5.0.3.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.8.13</version>
            </dependency>
        </dependencies>
    </project>
    

    2.创建业务层和dao层

    package com.itheima.service.impl;
    
    import com.itheima.service.IAccountService;
    
    //账户业务层实现类
    public class AccountServiceImpl implements IAccountService {
    
        public void saveAccount() {
            System.out.println("执行了保存");
        }
    
        public void updateAccount(int i) {
            System.out.println("执行了更新");
        }
    
        public int deleteAccount() {
            System.out.println("执行了删除");
            return 0;
        }
    }
    
    

    3.准备一个具有公共代码的类

    package com.itheima.utils;
    //用于记录日志的工具类,他里面提供了公共的代码
    public class Logger {
        //用于打印日志:计划让其在切入点方法执行之前执行(切入点方法就是业务层方法)
        public void printLog(){
            System.out.println("Logger类中的方法开始记录日志了");
        }
    }
    

    目的:在执行业务层的方法之前,先执行printLog方法,通过spring配置的方式来完成,不使用动态代理

    4.配置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.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd">
        <!--配置spring的Ioc,把service对象配置进来-->
        <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
    
        <!--spring中基于xml的AOP配置步骤
            1.把通知Bean也交给spring来管理
            2.使用aop:config标签表名开始AOP的配置
            3.使用aop:aspect标签表明配置切面
                    id属性:是给切面提供一个唯一标识
                    ref属性:是指定通知类bean的Id
            4.在aop:aspect标签的内部使用对象标签来配置通知的类型
                我们现在的示例是让printLog方法在切入点方法执行之前执行,所以是前置通知
                        method属性:用于指定Logger类中哪个方法是前置通知
                        pointcut属性:用于指定切入点表达式,该表达式含义指的是对业务层中哪些方法增强
                切入点表达式的写法:
                    关键字:execution(表达式)
                        表达式:访问修饰符  返回值 包名.包名.包名....类名.方法(参数列表)
        -->
        <!--配置Logger类-->
        <bean id="logger" class="com.itheima.utils.Logger"></bean>
    
        <!--配置AOP-->
        <aop:config>
            <!--配置切面-->
            <aop:aspect id="logAdvice" ref="logger">
                <!--配置通知类型,并且建立通知方法和切入点方法的关联-->
                <aop:before method="printLog" pointcut="execution(public void com.itheima.service.impl.AccountServiceImpl.saveAccount())"></aop:before>
            </aop:aspect>
    
        </aop:config>
    </beans>
    

    5.测试类

    package com.ithei.test;
    
    import com.itheima.service.IAccountService;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    //测试AOP的配置
    public class AOPTest {
        public static void main(String[] args) {
            //1.获取容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
            //2.获取UI小
            IAccountService as = (IAccountService)ac.getBean("accountService");
            //3.执行方法
            as.saveAccount();
        }
    }
    

    控制台输出:

    Logger类中的方法开始记录日志了
    执行了保存
    

    切入点表达式: execution(* com.itheima.service.impl..(..))

    四种通知的配置

    <!--配置AOP-->
        <aop:config>
            <!--配置切面-->
            <aop:aspect id="logAdvice" ref="logger">
                <!--配置通知类型,并且建立通知方法和切入点方法的关联-->
                <!--前置通知-->
                <aop:before method="beforePrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:before>
                <!--后置通知-->
                <aop:after-returning method="afterReturningPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-returning>
                <!--异常通知-->
                <aop:after-throwing method="afterThrowingPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after-throwing>
                <!--最终通知-->
                <aop:after method="afterPrintLog" pointcut="execution(* com.itheima.service.impl.*.*(..))"></aop:after>
            </aop:aspect>
        </aop:config>
    
  • 相关阅读:
    Html5响应式设计与实现广场
    hdu 4911 Inversion
    LAN远程重启server安全方法
    华丽的网上突出代码组件CodeMirror
    Edit Distance -- LeetCode
    FPGA合成编码
    SenchaTouch2.3.1 正在使用listpaging以及pullrefresh插入 分页演示样品做
    【白云观导引头】一首诗
    初步boost之pool图书馆学习笔记
    分段的作用
  • 原文地址:https://www.cnblogs.com/train99999/p/11216186.html
Copyright © 2011-2022 走看看