zoukankan      html  css  js  c++  java
  • day34_Spring学习笔记_02

    一、AOP

    1.1、AOP介绍

    1.1.1、什么是AOP?

    • 在软件业,AOP为Aspect Oriented Programming的缩写,意为:面向切面编程,通过预编译方式运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP(面向对象编程)的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
    • AOP采取横向抽取机制,取代了传统纵向继承体系重复性代码。如下图所示:
    • 经典应用:事务管理、性能监视、安全检查、缓存 、日志等。
    • Spring AOP使用纯Java实现,不需要专门的编译过程和类加载器,在运行期通过代理方式向目标类织入增强代码。
    • AspectJ是一个基于Java语言的AOP框架,从Spring2.0开始,Spring AOP引入对Aspect的支持,AspectJ扩展了Java语言,提供了一个专门的编译器,在编译时提供横向代码的织入。

    1.1.2、AOP实现原理

    • aop底层将采用代理机制进行实现。
    • 接口 + 实现类时 :spring采用 jdk 的 动态代理 Proxy。
    • 只有实现类时:spring 采用 cglib 字节码增强

    1.1.3、AOP术语【掌握】

    1. Target :目标类,需要被代理的类。本例中如:UserService
    2. Joinpoint(连接点) :所谓连接点是指那些可能被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。本例中如:UserService的所有的方法
    3. PointCut 切入点 :所谓切入点是指我们要对哪些Joinpoint进行拦截,即已经被增强的连接点。例如:addUser()
    4. Advice :通知/增强,增强的代码。例如:after()、before()
      所谓通知是指拦截到Joinpoint之后所要做的事情就是通知,通知分为前置通知、后置通知、异常通知、最终通知、环绕通知(即切面要完成的功能)。
    5. Weaving(织入) :是指把通知/增强advice应用到目标对象target来创建新的代理对象proxy的过程。
      spring采用动态代理织入,而AspectJ采用编译期织入和类装在期织入。
    6. Proxy :代理类,一个类被AOP织入增强后,就产生一个结果代理类。
    7. Aspect(切面) : 是切入点Pointcut和通知Advice(引介)的结合。
    8. Introduction(引介) :引介是一种特殊的通知,在不修改类代码的前提下,Introduction 可以在运行期为类动态地添加一些方法或Field。

    • 小结:
      一个线是一个特殊的面。
      一个切入点和一个通知,组成成一个特殊的面。
      详解如图01:

      详解如图02:

    1.2、手动方式

    1.2.1、JDK动态代理

    • JDK动态代理:是对“装饰者”设计模式的简化。JDK动态代理使用前提:必须有接口。
      1. 目标类:接口 + 实现类
      2. 切面类:用于存放通知,名称叫:MyAspect.java
      3. 工厂类:编写工厂生成代理
      4. 测试类

    1.2.1.1、目标类
    UserService.java

    // 目标接口
    public interface UserService {

        public void addUser();
        public void updateUser();
        public void deleteUser();
    }

    UserServiceImpl.java

    // 目标实现类,有接口
    public class UserServiceImpl implements UserService {

        @Override
        public void addUser() {
            System.out.println("a_proxy.a_jdk addUser");
        }

        @Override
        public void updateUser() {
            System.out.println("a_proxy.a_jdk updateUser");
        }

        @Override
        public void deleteUser() {
            System.out.println("a_proxy.a_jdk deleteUser");
        }
    }

    1.2.1.2、切面类
    MyAspect.java

    // 切面类
    public class MyAspect {
        public void before() {
            System.out.println("前方法");
        }

        public void after() {
            System.out.println("后方法");
        }
    }

    1.2.1.3、工厂类(自定义的)
    MyBeanFactory.java

    // 工厂类
    public class MyBeanFactory {
        public static UserService createService() {
            // 1、先有目标类对象
            final UserService userService = new UserServiceImpl();
            // 2、再有切面类
            final MyAspect myAspect = new MyAspect();
            /* 3、最后有代理类,将目标类(切入点)和切面类(通知)进行结合  =》  切面
             *  Proxy.newProxyInstance
             *      参数1:ClassLoader loader 类加载器,我们知道,动态代理类在运行时创建的,任何类都需要类加载器将其加载到内存。
             *          类加载器该如何写呢?
             *          答:一般情况下:当前类.class.getClassLoader()
             *              或者 目标类的实例.getClass().getClassLoader()
             * 
             *      参数2:Class[] interfaces 代理类需要实现的所有接口
             *          方式1:目标类的实例.getClass().getInterfaces()  注意:该方式只能获得自己接口,不能获得父元素接口
             *          方式2:new Class[]{UserService.class}   
             *              例如:jdbc 驱动   => DriverManager => 获得接口 Connection
             * 
             *      参数3:InvocationHandler h 处理类,是一个接口,必须进行实现类,一般情况下采用:匿名内部类
             *          该接口提供了一个 invoke 方法,代理类的每一个方法执行时,都将调用一次invoke 方法
             *              参数31:Object proxy       代理对象
             *              参数32:Method method      代理对象当前执行的方法的描述对象(反射)
             *                  执行的方法名:method.getName()
             *                  执行的方法:method.invoke(对象, 实际参数)
             *              参数33:Object[] args      方法的实际参数
             */

            UserService proxyService = (UserService) Proxy.newProxyInstance(
                MyAspect.class.getClassLoader(), 
                userService.getClass().getInterfaces(), 
                new InvocationHandler() {

                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 前执行
                        myAspect.before();

                        // 执行目标类的方法
                        Object obj = method.invoke(userService, args);

                        // 后执行
                        myAspect.after();

                        return obj;
                    }
                });
            return proxyService;
        }
    }

    1.2.1.4、测试类
    TestJDK.java

    // 测试类
    public class TestJDK {

        @Test
        public void demo01() {
            UserService userService = MyBeanFactory.createService();
            userService.addUser();
            userService.updateUser();
            userService.deleteUser();
        }
    }

    程度运行结果为:

    前方法
    a_proxy.a_jdk addUser
    后方法
    前方法
    a_proxy.a_jdk updateUser
    后方法
    前方法
    a_proxy.a_jdk deleteUser
    后方法
    • debug调试的结果:
    • JDK动态代理返回的是:$Proxy (id=34)

    1.2.2、CGLIB字节码增强

    • 没有接口,只有实现类。
    • 采用字节码增强框架 cglib,运行原理:在运行时,创建目标类的子类,从而对目标类进行增强。
    • 导入jar包: 自己导jar包(了解):
      • 核心包:hibernate-distribution-3.6.10.Finallibytecodecglibcglib-2.2.jar
      • 依赖包:struts-2.3.15.3appsstruts2-blankWEB-INFlibasm-3.3.jar
    • spring-core-3.2.0.RELEASE.jar 已经整合以上两个内容,所以我们只需要导入这个包就可以了,如下图所示:

      项目中的位置:

    1.2.2.1、目标类
    UserServiceImpl.java

    // 目标实现类,没接口
    public class UserServiceImpl {

        public void addUser() {
            System.out.println("a_proxy.b_cglib addUser");
        }

        public void updateUser() {
            System.out.println("a_proxy.b_cglib updateUser");
        }

        public void deleteUser() {
            System.out.println("a_proxy.b_cglib deleteUser");
        }
    }

    1.2.2.2、切面类
    MyAspect.java的代码同上 1.2.1.2、切面类 代码,这里不再赘述!

    1.2.2.3、工厂类(自定义的)
    MyBeanFactory.java

    // 工厂类
    public class MyBeanFactory {
        public static UserServiceImpl createService() {
            // 1、先有目标类对象
            final UserServiceImpl userServiceImpl = new UserServiceImpl();
            // 2、再有切面类对象
            final MyAspect myAspect = new MyAspect();

            // 3、最后有代理类,采用cglib,底层创建目标类的子类
            // 3.1、核心类
            Enhancer enhancer = new Enhancer();
            // 3.2 、先确定父类
            enhancer.setSuperclass(userServiceImpl.getClass());
            /* 3.3、 设置回调函数 ,MethodInterceptor接口  等效  jdk中的 InvocationHandler接口 
             *      intercept() 等效 jdk中的  invoke()
             *          参数1、参数2、参数3:和以invoke()方法的参数一样
             *          参数4:methodProxy 方法的代理
             */

            enhancer.setCallback(new MethodInterceptor() {

                @Override
                public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

                    // 前执行
                    myAspect.before();

                    // 执行目标类的方法
                    Object obj = method.invoke(userServiceImpl, args);
                    // 执行代理类的父类,就是执行目标类(目标类和代理类是斧子关系),相当于inwoke调用了2次
                    methodProxy.invokeSuper(proxy, args);

                    // 后执行
                    myAspect.after();

                    return obj;
                }});

            // 4、创建代理
            UserServiceImpl proxyService = (UserServiceImpl) enhancer.create();

            return proxyService;
        }
    }

    1.2.2.4、测试类
    TestJDK.java的代码同上 1.2.1.4、切面类 代码,这里不再赘述!
    程度运行结果为:

    前方法
    a_proxy.b_cglib addUser
    a_proxy.b_cglib addUser
    后方法
    前方法
    a_proxy.b_cglib updateUser
    a_proxy.b_cglib updateUser
    后方法
    前方法
    a_proxy.b_cglib deleteUser
    a_proxy.b_cglib deleteUser
    后方法
    • debug调试的结果:
    • CGLIB字节码增强返回的是:UserServiceImpl$$EnhancerByCGLIB$$157a2b67 (id=34)

    1.2.3、代理知识总结

    • Spring在运行期,生成动态代理对象,不需要特殊的编译器。
    • Spring AOP的底层就是通过JDK动态代理或CGLib动态代理技术为目标Bean执行横向织入的。
      1. 若目标对象实现了若干接口,spring使用JDK的java.lang.reflect.Proxy类代理。
      2. 若目标对象没有实现任何接口,spring使用CGLIB库生成目标对象的子类。
    • 程序中应优先对接口创建代理,便于程序解耦维护。
    • 标记为final的方法,不能被代理,因为无法进行覆盖。
      1. JDK动态代理,是针对接口生成子类,接口中的方法不能使用final修饰。
      2. CGLib动态代理,是针对目标类生产子类,因此目标类和目标类的方法是不能使用final修饰。
    • Spring只支持方法连接点,不提供属性连接。

    1.3、AOP联盟增强(通知)类型

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

    模拟环绕通知:

    环绕通知:`必须手动执行目标方法`
        try {
           // 前置通知
           // 执行目标方法
           // 后置通知
        } catch() {
           // 异常抛出通知
        }

    1.4、spring 编写代理:半自动

    • 让spring 给我们创建代理对象,我们从spring容器中手动的获取代理对象。
    • 导入jar包:
      • 核心jar包:4 + 1
      • AOP的jar包:AOP联盟(规范/接口)、spring-aop(实现)

    1.4.1、目标类

    UserService.java

    // 目标接口
    public interface UserService {

        public void addUser();
        public void updateUser();
        public void deleteUser();
    }

    UserServiceImpl.java

    // 目标实现类,有接口
    public class UserServiceImpl implements UserService {

        @Override
        public void addUser() {
            System.out.println("b_factory_bean addUser");
        }

        @Override
        public void updateUser() {
            System.out.println("b_factory_bean updateUser");
        }

        @Override
        public void deleteUser() {
            System.out.println("b_factory_bean deleteUser");
        }
    }

    1.4.2、切面类

    // 切面类
    /**
     * 切面类中需要删除之前自己写的通知,添加上AOP联盟提供的通知(即要增强的东西),需要实现不同接口,接口就是规范,从而就确定方法名称。
     *         采用“环绕通知” MethodInterceptor
     *
     */

    public class MyAspect implements MethodInterceptor {

        @Override
        public Object invoke(MethodInvocation mi) throws Throwable {

            System.out.println("我们的前代码");

            // 使用AOP联盟的环绕通知:必须手动执行目标方法
            Object obj = mi.proceed();

            System.out.println("我们的后代码");

            return obj;
        }
    }

    1.4.3、spring配置

    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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans 
                                  http://www.springframework.org/schema/beans/spring-beans.xsd"
    >

        <!-- 创建目标类对象 -->
        <bean id="userServiceId" class="com.itheima.b_factory_bean.UserServiceImpl"></bean>
        <!-- 创建切面类 -->
        <bean id="myAspectId" class="com.itheima.b_factory_bean.MyAspect"></bean>

        <!-- 创建代理类对象 
                因为我们使用的是工厂bean:FactoryBean,它的底层调用的是 getObject() 返回一个特殊的bean
                工厂bean的一个具体实现类:ProxyFactoryBean类,该类用于创建代理工厂bean,生产特殊的代理对象   
                    第一个属性:
                        interfaces :确定接口们
                            通过  <array> + <value> 可以设置多个值;
                            如果只有一个值时,可以简写  value=""
                        target :确定目标类
                        interceptorNames :通知,切面类的名称,类型是String[],如果设置一个值用value=""     注意:jdk1.8中不支持该属性!
                        optimize :强制使用cglib
                            <property name="optimize" value="true"></property>
                创建代理类对象的底层机制:
                    如果目标类有接口,就采用jdk 动态代理
                    如果目标类没有接口,就采用cglib 字节码增强
                    如果声明 optimize = true ,无论是否有接口,都采用cglib 字节码增强
        -->

        <bean id="proxyServiceId" class="org.springframework.aop.framework.ProxyFactory">
            <property name="interfaces" value="com.itheima.b_factory_bean.UserService"></property>
            <property name="target" ref="userServiceId"></property>
            <property name="interceptorNames" value="myAspectId"></property>
            <property name="optimize" value="true"></property>
            <!-- 
            <property name="interfaces">
                <array>
                    <value></value>
                    <value></value>
                    <value></value>
                </array>
            </property> 
            -->

        </bean>
    </beans>

    1.4.4、测试类

    TestFactoryBean.java

    // 测试类
    public class TestFactoryBean {

        @Test
        public void demo01() {
            String xmlPath = "com/itheima/b_factory_bean/beans.xml";
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
            // 获取代理类对象
            UserService userService = (UserService) applicationContext.getBean("proxyServiceId");

            userService.addUser();
            userService.updateUser();
            userService.deleteUser();
        }
    }

    1.5、spring aop编程:全自动【掌握】

    • 我们从spring容器获得的就是目标类,如果我们配置了aop,spring将自动生成代理对象。
    • 我们要确定目标类,使用aspectj 切入点表达式,要导入jar包:
      • 文件位置:spring-framework-3.0.2.RELEASE-dependenciesorg.aspectjcom.springsource.org.aspectj.weaver1.6.8.RELEASE

    1.5.1、目标类

    UserService.java 和 UserServiceImpl.java 代码 同 1.4.1、目标类 代码一样。

    1.5.2、切面类

    MyAspect.java 代码同 1.4.2、切面类 代码一样。

    1.5.3、spring配置


    beans.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"
    >

        <!-- 1、创建目标类对象 -->
        <bean id="userServiceId" class="com.itheima.c_spring_aop.UserServiceImpl"></bean>
        <!-- 2、创建切面类 (通知)-->
        <bean id="myAspectId" class="com.itheima.c_spring_aop.MyAspect"></bean>
        <!-- 3、aop编程 
             3.1、 导入命名空间
             3.2 、使用 <aop:config>进行配置
                    proxy-target-class="true" 声明使用cglib代理,否则默认使用jdk代理
                        <aop:pointcut> 切入点 ,从目标对象上来获得具体方法
                        <aop:advisor> 特殊的切面,只有一个通知 和 一个切入点
                            advice-ref 通知引用
                            pointcut-ref 切入点引用
             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="myAspectId" pointcut-ref="myPointCut"/>
        </aop:config>
    </beans>

    1.5.4、测试类

    TestFactoryBean.java

    package com.itheima.c_spring_aop;

    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;

    // 测试类
    public class TestSpringAOP {

        @Test
        public void demo01() {
            String xmlPath = "com/itheima/c_spring_aop/beans.xml";
            ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
            // 获取目标类对象
            UserService userService = (UserService) applicationContext.getBean("userServiceId");

            userService.addUser();
            userService.updateUser();
            userService.deleteUser();
        }
    }

    程度运行结果为:

    我们的前代码
    c_spring_aop addUser
    我们的后代码
    我们的前代码
    c_spring_aop updateUser
    我们的后代码
    我们的前代码
    c_spring_aop deleteUser
    我们的后代码

    二、使用 AspectJ 实现 AOP

    2.1、AspectJ 的介绍

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

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

    1.execution()  用于描述方法【掌握】
        语法:execution(修饰符  返回值  包.类.方法名(参数) throws异常)
            修饰符,一般省略
                public      公共方法
                *           任意
            返回值,不能省略
                void        返回没有值
                String      返回值字符串
                *           任意
            包,[可以省略]
                com.itheima.crm                 固定的包
                com.itheima.crm.*.service       crm包下面的任意子包,固定目录service(例如: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:pointcut expression="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')

    2.3、AspectJ 的通知类型

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

    模拟以上几个通知:

    环绕通知:around

    try {
        // 前置通知:before
        // 手动执行目标方法
        // 后置通知:afterRetruning
    catch() {
        // 抛出异常通知:afterThrowing
    finally {
        // 最终通知:after
    }
    • 要学习的5个实现类,如下图所示:

      jar包中的位置:

      源码解释01:

      源码解释02:

    2.4、导入jar包

    • 需要导入4个jar包:
      • aop 联盟规范
      • spring aop 实现
      • aspect 规范
      • spring aspect 实现
    • 如下如所示:

    2.5、基于xml

    • 思路:
      • 1、目标类:接口类 + 实现类
      • 2、切面类:编写多个通知,采用aspectj 的方法,所以通知名称任意(即方法名任意)
      • 3、aop编程,将通知应用到目标类
      • 4、测试类

    2.5.1、目标类

    UserService.java 和 UserServiceImpl.java 代码 同 1.4.1、目标类 代码一样。

    2.5.2、切面类

    MyAspect.java

    // 切面类,含有多个通知
    public class MyAspect {

        public void myBefore(JoinPoint joinPonint{
            System.out.println("我的前置通知:" + joinPonint.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 null;
        }

        public void myAfterThrowing(JoinPoint joinPoint, Throwable e{
            System.out.println("我的抛出异常通知 : " + e.getMessage());
        }

        public void myAfter(JoinPoint joinPoint{
            System.out.println("我的最终通知");
        }
    }

    2.5.3、spring配置

    beans.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"
    >

        <!-- 1、创建目标类对象 -->
        <bean id="userServiceId" class="com.itheima.d_aspect.a_xml.UserServiceImpl"></bean>
        <!-- 2、创建切面类 (通知)-->
        <bean id="myAspectId" class="com.itheima.d_aspect.a_xml.MyAspect"></bean>
        <!-- 3、aop编程 
            <aop:aspect>    将切面类,声明为“切面”,从而获得切面类的通知们(方法们)
                ref 切面类引用(id)
            <aop:pointcut>  声明一个切入点,该切入点所有的通知都可以使用。
                expression  切入点表达式
                id  名称,用于其它通知的引用
        -->

        <aop:config>
            <aop:aspect ref="myAspectId">
                <aop:pointcut expression="execution(* com.itheima.d_aspect.a_xml.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:before method="myBefore" pointcut-ref="myPointCut"/> -->
                <!-- <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret"/> -->
                <!-- <aop:around method="myAround" pointcut-ref="myPointCut"/> -->
                <!-- <aop:after-throwing method="myAfterThrowing" pointcut-ref="myPointCut" throwing="e"/> -->
                <aop:after method="myAfter" pointcut-ref="myPointCut"/>
            </aop:aspect>
        </aop:config>

    </beans>

    2.6、基于注解(替代xml)

    2.6.1、替换bean

        <!-- 1、创建目标类对象 -->
        <bean id="userServiceId" class="com.itheima.d_aspect.b_annotation.UserServiceImpl"></bean>
        <!-- 2、创建切面类 (通知)-->
        <bean id="myAspectId" class="com.itheima.d_aspect.b_annotation.MyAspect"></bean>
    • 以上配置对应的类如下:

       

    • 注意:需要配置扫描,注解使用前提,必须添加命名空间,让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.itheima.d_aspect.b_annotation"></context:component-scan>
        <!-- 2、确定 aop注解生效 -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

    2.6.2、替换aop

    • 声明 切面
    以前:
        <aop:aspect ref="myAspectId">
    现在:
        // 切面类,含有多个通知
        @Component
        @Aspect
        public class MyAspect {
    • 替换 前置通知
    现在:
        <aop:before method="myBefore" pointcut="execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))"/>
    以前:
        // 切入点在当前有效
        @Before("execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))")
        public void myBefore(JoinPoint joinPonint{
            System.out.println("我的前置通知:" + joinPonint.getSignature().getName());
        }
    • 替换 公共切入点
    以前:
        <aop:pointcut expression="execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))" id="myPointCut"/>
    现在:
        // 声明公共切入点
        @Pointcut("execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))")
        private void myPointCut() {
        }
    • 替换 后置通知
    以前:
        <aop:after-returning method="myAfterReturning" pointcut-ref="myPointCut" returning="ret"/>
    现在:
        @AfterReturning(value="myPointCut()", returning="ret")
        public void myAfterReturning(JoinPoint joinPoint, Object ret{
            System.out.println("我的后置通知 : " + joinPoint.getSignature().getName() + ", --> " + ret);
        }

    详解如下:


    • 替换 环绕通知
    以前:
        <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 null;
        }
    • 替换 抛出异常通知
    以前:
        <aop:after-throwing method="myAfterThrowing" pointcut="execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))" throwing="e"/>
    现在:
        @AfterThrowing(value="execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))" ,throwing="e")
        public void myAfterThrowing(JoinPoint joinPoint, Throwable e{
            System.out.println("我的抛出异常通知 : " + e.getMessage());
        }
    • 替换 最终通知
    以前:
        <aop:after method="myAfter" pointcut-ref="myPointCut"/>
    现在:
        @After("myPointCut()")
        public void myAfter(JoinPoint joinPoint{
            System.out.println("我的最终通知");
        }

    2.6.3、切面类

    MyAspect.java

    package com.itheima.d_aspect.b_annotation;

    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.After;
    import org.aspectj.lang.annotation.AfterReturning;
    import org.aspectj.lang.annotation.AfterThrowing;
    import org.aspectj.lang.annotation.Around;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.aspectj.lang.annotation.Pointcut;
    import org.springframework.stereotype.Component;

    // 切面类,含有多个通知
    @Component
    @Aspect
    public class MyAspect {

        // 切入点在当前有效
        // @Before("execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))")
        public void myBefore(JoinPoint joinPonint) {
            System.out.println("我的前置通知:" + joinPonint.getSignature().getName());
        }

        // 声明公共切入点
        // @Pointcut("execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))")
        private void myPointCut() {
        }

        // @AfterReturning(value="myPointCut()", returning="ret")
        public void 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 null;
        }

        @AfterThrowing(value="execution(* com.itheima.d_aspect.b_annotation.UserServiceImpl.*(..))" ,throwing="e")
        public void myAfterThrowing(JoinPoint joinPoint, Throwable e) {
            System.out.println("我的抛出异常通知 : " + e.getMessage());
        }

        @After("myPointCut()")
        public void myAfter(JoinPoint joinPoint) {
            System.out.println("我的最终通知");
        }
    }

    2.6.4、spring配置

    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: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_annotation"></context:component-scan>
        <!-- 2、确定 aop注解生效 -->
        <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    </beans>

    2.6.5、aop注解总结

    切面
        @Aspect     用于声明切面,修饰切面类,从而获得通知。
    通知
        @Before     前置通知
        @AfterReturning 后置通知
        @Around     环绕通知
        @AfterThrowing  抛出异常通知
        @After      最终通知
    切入点
        @PointCut   该注解修饰方法格式为:private void xxx(){}  我们通过“方法名”获得切入点的引用。

    三、JdbcTemplate

    • JdbcTemplate是spring 提供用于操作JDBC的工具类,类似:DBUtils。
    • JdbcTemplate依赖连接池DataSource(数据源)

    3.1、环境搭建

    3.1.1、创建表

    CREATE DATABASE day34;
    USE day34;

    CREATE TABLE t_user(
      id INT PRIMARY KEY AUTO_INCREMENT,
      username VARCHAR(50),
      PASSWORD VARCHAR(32)
    );

    INSERT INTO t_user(username,PASSWORDVALUES('jack','1234');
    INSERT INTO t_user(username,PASSWORDVALUES('rose','5678');

    3.1.2、导入jar包

    如下图所示:

    3.1.3、创建数据模型

    User.java

    package com.itheima.domain;

    public class User {
        private Integer id;
        private String username;
        private String password;
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            this.id = id;
        }
        public String getUsername() {
            return username;
        }
        public void setUsername(String username) {
            this.username = username;
        }
        public String getPassword() {
            return password;
        }
        public void setPassword(String password) {
            this.password = password;
        }
    }

    3.2、使用api(了解)

    package com.itheima.b_api;

    import org.apache.commons.dbcp.BasicDataSource;
    import org.springframework.jdbc.core.JdbcTemplate;

    public class TestAPI {
        public static void main(String[] args) {

            // 1、创建数据源(连接池), 使用dbcp
            BasicDataSource dataSource = new BasicDataSource();
            // 设置基本4项
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            dataSource.setUrl("jdbc:mysql://localhost:3306/day34");
            dataSource.setUsername("root");
            dataSource.setPassword("root");

            // 2、 创建模板
            JdbcTemplate jdbcTemplate = new JdbcTemplate();
            jdbcTemplate.setDataSource(dataSource);

            // 3、 通过api操作
            jdbcTemplate.update("insert into t_user(username,password) values(?,?);""tom""998");
        }
    }

    3.3、配置DBCP

    beans.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: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"
    >


        <!-- 创建数据源对象,需要注入基本四项 -->
        <bean id="dataSourceId" class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/day34"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>

        <!-- 创建模板对象 ,需要注入数据源-->
        <bean id="jdbcTemplateId" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSourceId"></property>
        </bean>

        <!-- 配置dao对象 -->
        <bean id="userDaoId" class="com.itheima.c_dbcp.UserDao">
            <property name="jdbcTemplate" ref="jdbcTemplateId"></property>
        </bean>

    </beans>

    3.4、配置C3P0

    beans.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: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"
    >


        <!-- 创建数据源对象,c3p0,需要注入基本四项 -->
        <bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day34"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>

        <!-- 创建模板对象 ,需要注入数据源-->
        <bean id="jdbcTemplateId" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSourceId"></property>
        </bean>

        <!-- 配置dao对象,需要注入jdbc模板  -->
        <bean id="userDaoId" class="com.itheima.d_c3p0.UserDao">
            <property name="jdbcTemplate" ref="jdbcTemplateId"></property>
        </bean>

    </beans>

    3.5、使用JdbcDaoSupport

        // jdbc的模板将由spring注入
        private JdbcTemplate jdbcTemplate;

        public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }

    由于每一个dao里面都需要将jdbc模板代码使用Spring注入进来(如上代码),比较麻烦,所以Spring就想了一个招:把jdbc模板代码写到一个父类中,然后让dao去继承它。这个父类叫做JdbcDaoSupport。

    3.5.1、dao层

    package com.itheima.e_JdbcDaoSupport;

    import java.util.List;

    import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
    import org.springframework.jdbc.core.support.JdbcDaoSupport;

    import com.itheima.a_domain.User;

    public class UserDao extends JdbcDaoSupport {

        // 更新用户
        public void update(User user) {
            String sql = "update t_user set username=?,password=? where id =?";
            Object[] args = { user.getUsername(), user.getPassword(), user.getId() };
            this.getJdbcTemplate().update(sql, args);
        }

        // 查询所有
        public List<User> findAll() {
            return this.getJdbcTemplate().query("select * from t_user", ParameterizedBeanPropertyRowMapper.newInstance(User.class));
        }
    }

    3.5.2、spring配置文件

    beans.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: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"
    >


        <!-- 创建数据源对象,c3p0,需要注入基本四项 -->
        <bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/day34"></property>
            <property name="user" value="root"></property>
            <property name="password" value="root"></property>
        </bean>

        <!-- 配置dao对象,需要注入jdbc模板  ,需要注入数据源
             由于dao继承了 JdbcDaoSupport,之后只需要注入数据源即可,底层将自动创建模板。
        -->

        <bean id="userDaoId" class="com.itheima.e_JdbcDaoSupport.UserDao">
            <property name="dataSource" ref="dataSourceId"></property>
        </bean>

    </beans>

    3.5.3、JdbcDaoSupport源码分析

     

    3.6、配置properties

    以后在开发中,我们会将创建数据源对象时需要注入的基本四项,放在一个properties文件中。
    JdbcInfo.properties

    jdbc.driverClass=com.mysql.jdbc.Driver
    jdbc.jdbcUrl=jdbc:mysql://localhost:3306/day34
    jdbc.user=root
    jdbc.password=root

    beans.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: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"
    >

        <!-- 加载配置文件 JdbcInfo.properties
             "classpath:" 该前缀表示在src目录下
              在配置文件中通过  ${key} 获得配置文件 内容(值)
        -->

        <context:property-placeholder location="classpath:com/itheima/f_properties/jdbcInfo.properties"/>

        <!-- 创建数据源对象,c3p0,需要注入基本四项 -->
        <bean id="dataSourceId" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="${jdbc.driverClass}"></property>
            <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
            <property name="user" value="${jdbc.user}"></property>
            <property name="password"  value="${jdbc.password}"></property>
        </bean>

        <!-- 配置dao对象,需要注入jdbc模板  ,需要注入数据源
             由于dao继承了 JdbcDaoSupport,之后只需要注入数据源即可,底层将自动创建模板。
        -->

        <bean id="userDaoId" class="com.itheima.f_properties.UserDao">
            <property name="dataSource" ref="dataSourceId"></property>
        </bean>

    </beans>
  • 相关阅读:
    优麒麟(UbuntuKylin)不是国产Linux操作系统
    Win10開始菜单打不开
    五步让你玩转CocoaPods
    设计模式学习笔记之适配器模式
    感谢各位亲们的大力支持,免费的HTML5学习课程《HTML5网页开发实例具体解释》连载已经结束了!
    iOS获取时间、日期
    leetcode NO.1 两数之和 (python3实现)
    leetcode NO.53 最大子序列和 (python3实现)
    [笔记]《算法图解》第六章 广度搜索优先
    [笔记]《算法图解》第四章 快速排序
  • 原文地址:https://www.cnblogs.com/chenmingjun/p/9413977.html
Copyright © 2011-2022 走看看