重拾Java EE——Spring(2)高阶

1 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(连接点):所谓连接点是指那些可能被拦截到的方法。例如:所有的方法
3.PointCut 切入点:已经被增强的连接点。例如:addUser()
4.advice 通知/增强,增强代码。例如:after、before
5. Weaving(织入):是指把增强advice应用到目标对象target来创建新的代理对象proxy的过程.

6.proxy 代理类.
7. Aspect(切面): 是切入点pointcut和通知advice的结合
一个线是一个特殊的面。
一个切入点和一个通知,组成成一个特殊的面。

1.2 手动方式

1.2.1 JDK动态代理

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

1.2.1.1 目标类

public interface UserService {

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

}

1.2.1.2 切面类

public class MyAspect {
    public void before(){
        System.out.println("鸡首");
    }
    public void after(){
        System.out.println("牛后");
    }
}

1.2.1.3 工厂

public class MyBeanFactory {

    public static UserService createService(){
        //1 目标类
        final UserService userService = new UserServiceImpl();
        //2切面类
        final MyAspect myAspect = new MyAspect();
        /* 3 代理类:将目标类(切入点)和 切面类(通知) 结合 --> 切面
         *  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 :方法实际参数
         * 
         */
        UserService proxService = (UserService)Proxy.newProxyInstance(
                                MyBeanFactory.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 proxService;
    }

}

1.2.1.4 测试

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

1.2.2 CGLIB字节码增强

  • 没有接口,只有实现类。
  • 采用字节码增强框架 cglib,在运行时 创建目标类的子类,从而对目标类进行增强。
  • 导入jar包:
    自己导包(了解):
    核心:hibernate-distribution-3.6.10.Final\lib\bytecode\cglib\cglib-2.2.jar
    依赖:struts-2.3.15.3\apps\struts2-blank\WEB-INF\lib\asm-3.3.jar
    spring-core..jar 已经整合以上两个内容

1.2.2.1 工厂类

public class MyBeanFactory {

    public static UserServiceImpl createService(){
        //1 目标类
        final UserServiceImpl userService = new UserServiceImpl();
        //2切面类
        final MyAspect myAspect = new MyAspect();
        // 3.代理类 ,采用cglib,底层创建目标类的子类
        //3.1 核心类
        Enhancer enhancer = new Enhancer();
        //3.2 确定父类
        enhancer.setSuperclass(userService.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(userService, args);
                // * 执行代理类的父类 ,执行目标类 (目标类和代理类 父子关系)
                methodProxy.invokeSuper(proxy, args);

                //后
                myAspect.after();

                return obj;
            }
        });
        //3.4 创建代理
        UserServiceImpl proxService = (UserServiceImpl) enhancer.create();

        return proxService;
    }

}

1.3 AOP联盟通知类型

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

环绕通知,必须手动执行目标方法

try{
   //前置通知
   //执行目标方法
   //后置通知
} catch(){
   //抛出异常通知
}

1.4 spring编写代理:半自动

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

1.4.1 目标类

public interface UserService {

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

}

1.4.2 切面类

/**
 * 切面类中确定通知,需要实现不同接口,接口就是规范,从而就确定方法名称。
 * * 采用“环绕通知” MethodInterceptor
 *
 */
public class MyAspect implements MethodInterceptor {

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

        System.out.println("前3");

        //手动执行目标方法
        Object obj = mi.proceed();

        System.out.println("后3");
        return obj;
    }
}

1.4.3 spring配置

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

    <!-- 3 创建代理类 
        * 使用工厂bean FactoryBean ,底层调用 getObject() 返回特殊bean
        * ProxyFactoryBean 用于创建代理工厂bean,生成特殊代理对象
            interfaces : 确定接口们
                通过<array>可以设置多个值
                只有一个值时,value=""
            target : 确定目标类
            interceptorNames : 通知 切面类的名称,类型String[],如果设置一个值 value=""
            optimize :强制使用cglib
                <property name="optimize" value="true"></property>
        底层机制
            如果目标类有接口,采用jdk动态代理
            如果没有接口,采用cglib 字节码增强
            如果声明 optimize = true ,无论是否有接口,都采用cglib

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

1.4.4 测试

“`java
@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-dependencies\org.aspectj\com.springsource.org.aspectj.weaver\1.6.8.RELEASE
 ![](https://upload-images.jianshu.io/upload_images/3034232-98cc6fba8881c37f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


### 1.5.1   spring配置
![](https://upload-images.jianshu.io/upload_images/3034232-1d8bd2027d27a200.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

 ```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代理
            <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.2 测试

    @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();
    }


2 AspectJ

2.1 介绍

  • 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包下面子包任意 (例如: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 通知类型,只定义类型名称。已经方法格式。
  • 个数:6种,知道5种,掌握1中。
    before:前置通知(应用:各种校验)
    在方法执行前执行,如果通知抛出异常,阻止方法运行
    afterReturning:后置通知(应用:常规数据处理)
    方法正常返回后执行,如果方法中抛出异常,通知无法执行
    必须在方法执行后才执行,所以可以获得方法的返回值。
    around:环绕通知(应用:十分强大,可以做任何事情)
    方法执行前后分别执行,可以阻止方法的执行
    必须手动执行目标方法
    afterThrowing:抛出异常通知(应用:包装异常信息)
    方法抛出异常后执行,如果方法没有抛出异常,无法执行
    after:最终通知(应用:清理现场)
    方法执行完毕后执行,无论方法中是否出现异常
    环绕
try{
     //前置:before
    //手动执行目标方法
    //后置:afterRetruning
} catch(){
    //抛出异常 afterThrowing
} finally{
    //最终 after
}
 ```
![](https://upload-images.jianshu.io/upload_images/3034232-af1930ab6b512a72.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![](https://upload-images.jianshu.io/upload_images/3034232-770d3a79f084e6c4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![](https://upload-images.jianshu.io/upload_images/3034232-cca8e01f0a635ed6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![](https://upload-images.jianshu.io/upload_images/3034232-79eac23956e88fff.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)







## 2.4  导入jar包 
-  4个:
    aop联盟规范
    spring aop 实现
    aspect 规范
    spring aspect 实现
 ![](https://upload-images.jianshu.io/upload_images/3034232-949f2ed503ae5e55.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)



## 2.5  基于xml
1.目标类:接口 + 实现
2.切面类:编写多个通知,采用aspectj 通知名称任意(方法名任意)
3.aop编程,将通知应用到目标类
4.测试

### 2.5.1   切面类

```java

/**
 * 切面类,含有多个通知
 */
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("最终通知");
    }

}




<div class="se-preview-section-delimiter"></div>

2.5.2 spring配置

<!-- 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 切面类引用
        <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:after method="myAfter" pointcut-ref="myPointCut"/>



        </aop:aspect>
    </aop:config>




<div class="se-preview-section-delimiter"></div>

2.6 基于注解

2.6.1 替换bean

<!-- 1 创建目标类 -->
    <bean id="userServiceId" class="com.itheima.d_aspect.b_anno.UserServiceImpl"></bean>
    <!-- 2 创建切面类(通知) -->
    <bean id="myAspectId" class="com.itheima.d_aspect.b_anno.MyAspect"></bean>
 ```
![](https://upload-images.jianshu.io/upload_images/3034232-363990443f308b41.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![](https://upload-images.jianshu.io/upload_images/3034232-4a66aa6c9ddecd53.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


-  注意:扫描





<div class="se-preview-section-delimiter"></div>

```xml
<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_anno"></context:component-scan>

2.6.2 替换aop

  • 必须进行aspectj 自动代理
<!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
  • 声明切面
 <aop:aspect ref="myAspectId">

  • 替换前置通知
<aop:before method="myBefore" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))"/>
    //切入点当前有效
    @Before("execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))")
    public void myBefore(JoinPoint joinPoint){
        System.out.println("前置通知 : " + joinPoint.getSignature().getName());
    }
  • 替换 公共切入点
<aop:pointcut expression="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" id="myPointCut"/>
//声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.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);
    }

 ```

![](https://upload-images.jianshu.io/upload_images/3034232-1070d5a7d2221721.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
-  替换环绕

```xml
<aop:around method="myAround" pointcut-ref="myPointCut"/>




<div class="se-preview-section-delimiter"></div>
@Around(value = "myPointCut()")
    public Object myAround(ProceedingJoinPoint joinPoint) throws Throwable{
        System.out.println("前");
        //手动执行目标方法
        Object obj = joinPoint.proceed();

        System.out.println("后");
        return obj;
    }




<div class="se-preview-section-delimiter"></div>
  • 替换抛出异常
<aop:after-throwing method="myAfterThrowing" pointcut="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" throwing="e"/>




<div class="se-preview-section-delimiter"></div>
@AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.UserServiceImpl.*(..))" ,throwing="e")
    public void myAfterThrowing(JoinPoint joinPoint,Throwable e){
        System.out.println("抛出异常通知 : " + e.getMessage());
    }




<div class="se-preview-section-delimiter"></div>

2.6.3 切面类

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

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

    //声明公共切入点
    @Pointcut("execution(* com.itheima.d_aspect.b_anno.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 obj;
    }

//  @AfterThrowing(value="execution(* com.itheima.d_aspect.b_anno.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("最终通知");
    }

}





<div class="se-preview-section-delimiter"></div>

2.6.4 spring配置

<!-- 1.扫描 注解类 -->
    <context:component-scan base-package="com.itheima.d_aspect.b_anno"></context:component-scan>

    <!-- 2.确定 aop注解生效 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>




<div class="se-preview-section-delimiter"></div>

2.6.5 aop注解总结

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




<div class="se-preview-section-delimiter"></div>


3 JdbcTemplate

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

3.1 环境搭建

3.1.1 创建表

create database ee19_spring_day02;
use ee19_spring_day02;
create table t_user(
  id int primary key auto_increment,
  username varchar(50),
  password varchar(32)
);

insert into t_user(username,password) values('jack','1234');
insert into t_user(username,password) values('rose','5678');




<div class="se-preview-section-delimiter"></div>

3.1.2 导入jar包

3.1.3 javabean

package com.itheima.domain;

public class User {

    private Integer id;
    private String username;
    private String password;




<div class="se-preview-section-delimiter"></div>

3.2 使用api(了解)

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/ee19_spring_day02");
        dataSource.setUsername("root");
        dataSource.setPassword("1234");


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


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

    }




<div class="se-preview-section-delimiter"></div>

3.3 配置DBCP

<!-- 创建数据源 -->
    <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/ee19_spring_day02"></property>
        <property name="username" value="root"></property>
        <property name="password" value="1234"></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>




<div class="se-preview-section-delimiter"></div>

3.4 配置C3P0

<!-- 创建数据源 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/ee19_spring_day02"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>




<div class="se-preview-section-delimiter"></div>

3.5 使用JdbcDaoSupport

3.5.1 dao层

3.5.2 spring配置文件

    <!-- 配置dao 
        * dao 继承 JdbcDaoSupport,之后只需要注入数据源,底层将自动创建模板
    -->
    <bean id="userDaoId" class="com.itheima.e_jdbcdaosupport.UserDao">
        <property name="dataSource" ref="dataSourceId"></property>
    </bean>




<div class="se-preview-section-delimiter"></div>

3.5.3 源码分析

3.6 配置properties

3.6.1 properties文件

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




<div class="se-preview-section-delimiter"></div>

3.6.2 spring配置

<!-- 加载配置文件 
        "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>





<div class="se-preview-section-delimiter"></div>


4 事务管理

4.1 回顾事务

  • 事务:一组业务操作ABCD,要么全部成功,要么全部不成功。
  • 特性:ACID
    原子性:整体
    一致性:完成
    隔离性:并发
    持久性:结果
  • 隔离问题:
    脏读:一个事务读到另一个事务没有提交的数据
    不可重复读:一个事务读到另一个事务已提交的数据(update)
    虚读(幻读):一个事务读到另一个事务已提交的数据(insert)
  • 隔离级别:
    read uncommitted:读未提交。存在3个问题
    read committed:读已提交。解决脏读,存在2个问题
    repeatable read:可重复读。解决:脏读、不可重复读,存在1个问题。
    serializable :串行化。都解决,单事务。

  • mysql 事务操作–简单
ABCD 一个事务
Connection conn = null;
try{
  //1 获得连接
  conn = ...;
  //2 开启事务
  conn.setAutoCommit(false);
  A
  B
  C
  D
  //3 提交事务
  conn.commit();
} catche(){
  //4 回滚事务
  conn.rollback();
}




<div class="se-preview-section-delimiter"></div>
  • mysql 事务操作–Savepoint
需求:AB(必须),CD(可选) 
Connection conn = null;
Savepoint savepoint = null;  //保存点,记录操作的当前位置,之后可以回滚到指定的位置。(可以回滚一部分)
try{
  //1 获得连接
  conn = ...;
  //2 开启事务
  conn.setAutoCommit(false);
  A
  B
  savepoint = conn.setSavepoint();
  C
  D
  //3 提交事务
  conn.commit();
} catche(){
  if(savepoint != null){   //CD异常
     // 回滚到CD之前
     conn.rollback(savepoint);
     // 提交AB
     conn.commit();
  } else{   //AB异常
     // 回滚AB
     conn.rollback();
  }
}




<div class="se-preview-section-delimiter"></div>

4.2 事务管理介绍

4.2.1 导入jar包

transaction –> tx

4.2.2 三个顶级接口

  • PlatformTransactionManager 平台事务管理器,spring要管理事务,必须使用事务管理器
    进行事务配置时,必须配置事务管理器。
  • TransactionDefinition:事务详情(事务定义、事务属性),spring用于确定事务具体详情,
    例如:隔离级别、是否只读、超时时间 等
    进行事务配置时,必须配置详情。spring将配置项封装到该对象实例。
  • TransactionStatus:事务状态,spring用于记录当前事务运行状态。例如:是否有保存点,事务是否完成。
    spring底层根据状态进行相应操作。

4.2.3 PlatformTransactionManager 事务管理器

  • 导入jar包:需要时平台事务管理器的实现类

  • 常见的事务管理器
    DataSourceTransactionManager ,jdbc开发时事务管理器,采用JdbcTemplate
    HibernateTransactionManager,hibernate开发时事务管理器,整合hibernate

  • api详解
TransactionStatus getTransaction(TransactionDefinition definition) ,事务管理器 通过“事务详情”,获得“事务状态”,从而管理事务。
void commit(TransactionStatus status)  根据状态提交
void rollback(TransactionStatus status) 根据状态回滚




<div class="se-preview-section-delimiter"></div>

4.2.4 TransactionStatus

4.2.5 TransactionDefinition

  • 传播行为:在两个业务之间如何共享事务。
PROPAGATION_REQUIRED , required , 必须  【默认值】
    支持当前事务,A如果有事务,B将使用该事务。
    如果A没有事务,B将创建一个新的事务。
PROPAGATION_SUPPORTS ,supports ,支持
    支持当前事务,A如果有事务,B将使用该事务。
    如果A没有事务,B将以非事务执行。
PROPAGATION_MANDATORY,mandatory ,强制
    支持当前事务,A如果有事务,B将使用该事务。
    如果A没有事务,B将抛异常。
PROPAGATION_REQUIRES_NEW , requires_new ,必须新的
    如果A有事务,将A的事务挂起,B创建一个新的事务
    如果A没有事务,B创建一个新的事务
PROPAGATION_NOT_SUPPORTED ,not_supported ,不支持
    如果A有事务,将A的事务挂起,B将以非事务执行
    如果A没有事务,B将以非事务执行
PROPAGATION_NEVER ,never,从不
    如果A有事务,B将抛异常
    如果A没有事务,B将以非事务执行
PROPAGATION_NESTED ,nested ,嵌套
    A和B底层采用保存点机制,形成嵌套事务。




<div class="se-preview-section-delimiter"></div>

掌握:PROPAGATION_REQUIRED、PROPAGATION_REQUIRES_NEW、PROPAGATION_NESTED

4.3 案例:转账

4.3.1 搭建环境

4.3.1.1 创建表

create database ee19_spring_day03;
use ee19_spring_day03;
create table account(
  id int primary key auto_increment,
  username varchar(50),
  money int
);
insert into account(username,money) values('jack','10000');
insert into account(username,money) values('rose','10000');




<div class="se-preview-section-delimiter"></div>

4.3.1.2 导入jar包

  • 核心:4+1
  • aop : 4 (aop联盟、spring aop、aspectj规范、spring aspect)
  • 数据库:2 (jdbc/tx)
  • 驱动:mysql
  • 连接池:c3p0

4.3.1.3 dao层

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    @Override
    public void out(String outer, Integer money) {
        this.getJdbcTemplate().update("update account set money = money - ? where username = ?", money,outer);
    }

    @Override
    public void in(String inner, Integer money) {
        this.getJdbcTemplate().update("update account set money = money + ? where username = ?", money,inner);
    }

}




<div class="se-preview-section-delimiter"></div>

4.3.1.4 service层

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    @Override
    public void transfer(String outer, String inner, Integer money) {
        accountDao.out(outer, money);
        //断电
//      int i = 1/0;
        accountDao.in(inner, money);
    }

}





<div class="se-preview-section-delimiter"></div>

4.3.1.5 spring配置

    <!-- 1 datasource -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ee19_spring_day03"></property>
        <property name="user" value="root"></property>
        <property name="password" value="1234"></property>
    </bean>

    <!-- 2 dao  -->
    <bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 3 service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
    </bean>




<div class="se-preview-section-delimiter"></div>

4.3.1.6 测试

    @Test
    public void demo01(){
        String xmlPath = "applicationContext.xml";
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
        AccountService accountService =  (AccountService) applicationContext.getBean("accountService");
        accountService.transfer("jack", "rose", 1000);
    }




<div class="se-preview-section-delimiter"></div>

4.3.2 手动管理事务(了解)

  • spring底层使用 TransactionTemplate 事务模板进行操作。
  • 操作
    1.service 需要获得 TransactionTemplate
    2.spring 配置模板,并注入给service
    3.模板需要注入事务管理器
    4.配置事务管理器:DataSourceTransactionManager ,需要注入DataSource

4.3.2.1 修改service

    //需要spring注入模板
    private TransactionTemplate transactionTemplate;
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }
    @Override
    public void transfer(final String outer,final String inner,final Integer money) {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus arg0) {
                accountDao.out(outer, money);
                //断电
//              int i = 1/0;
                accountDao.in(inner, money);
            }
        });

    }




<div class="se-preview-section-delimiter"></div>

4.3.2.2 修改spring配置

<!-- 3 service -->
    <bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
        <property name="accountDao" ref="accountDao"></property>
        <property name="transactionTemplate" ref="transactionTemplate"></property>
    </bean>

    <!-- 4 创建模板 -->
    <bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
        <property name="transactionManager" ref="txManager"></property>
    </bean>

    <!-- 5 配置事务管理器 ,管理器需要事务,事务从Connection获得,连接从连接池DataSource获得 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>




<div class="se-preview-section-delimiter"></div>

4.3.3 工厂bean 生成代理:半自动

  • spring提供 管理事务的代理工厂bean TransactionProxyFactoryBean
    1.getBean() 获得代理对象
    2.spring 配置一个代理

4.3.3.1 spring配置

<!-- 4 service 代理对象 
        4.1 proxyInterfaces 接口 
        4.2 target 目标类
        4.3 transactionManager 事务管理器
        4.4 transactionAttributes 事务属性(事务详情)
            prop.key :确定哪些方法使用当前事务配置
            prop.text:用于配置事务详情
                格式:PROPAGATION,ISOLATION,readOnly,-Exception,+Exception
                    传播行为        隔离级别    是否只读        异常回滚        异常提交
                例如:
                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop> 默认传播行为,和隔离级别
                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop> 只读
                    <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,+java.lang.ArithmeticException</prop>  有异常扔提交
    -->
    <bean id="proxyAccountService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="proxyInterfaces" value="com.itheima.service.AccountService"></property>
        <property name="target" ref="accountService"></property>
        <property name="transactionManager" ref="txManager"></property>
        <property name="transactionAttributes">
            <props>
                <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>
            </props>
        </property>
    </bean>


    <!-- 5 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>





<div class="se-preview-section-delimiter"></div>

4.3.3.2 测试

4.3.4 AOP 配置基于xml【掌握】

  • 在spring xml 配置aop 自动生成代理,进行事务的管理
    1.配置管理器
    2.配置事务详情
    3.配置aop
<!-- 4 事务管理 -->
    <!-- 4.1 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 4.2 事务详情(事务通知)  , 在aop筛选基础上,对ABC三个确定使用什么样的事务。例如:AC读写、B只读 等
        <tx:attributes> 用于配置事务详情(属性属性)
            <tx:method name=""/> 详情具体配置
                propagation 传播行为 , REQUIRED:必须;REQUIRES_NEW:必须是新的
                isolation 隔离级别
    -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    <!-- 4.3 AOP编程,目标类有ABCD(4个连接点),切入点表达式 确定增强的连接器,从而获得切入点:ABC -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.itheima.service..*.*(..))"/>
    </aop:config>




<div class="se-preview-section-delimiter"></div>

4.3.5 AOP配置基于注解【掌握】

  • 1.配置事务管理器,将并事务管理器交予spring
  • 2.在目标类或目标方法添加注解即可 @Transactional

4.3.5.1 spring配置

<!-- 4 事务管理 -->
    <!-- 4.1 事务管理器 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 4.2 将管理器交予spring 
        * transaction-manager 配置事务管理器
        * proxy-target-class
            true : 底层强制使用cglib 代理
    -->
    <tx:annotation-driven transaction-manager="txManager"/>




<div class="se-preview-section-delimiter"></div>

4.3.5.2 service 层

@Transactional
public class AccountServiceImpl implements AccountService {




<div class="se-preview-section-delimiter"></div>

4.3.5.3 事务详情配置

@Transactional(propagation=Propagation.REQUIRED , isolation = Isolation.DEFAULT)
public class AccountServiceImpl implements AccountService {




<div class="se-preview-section-delimiter"></div>


5 整合Junit

  • 导入jar包
    基本 :4+1
    测试:spring-test…jar

1.让Junit通知spring加载配置文件
2.让spring容器自动进行注入

  • 修改测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class TestApp {

    @Autowired  //与junit整合,不需要在spring xml配置扫描
    private AccountService accountService;

    @Test
    public void demo01(){
//      String xmlPath = "applicationContext.xml";
//      ApplicationContext applicationContext = new ClassPathXmlApplicationContext(xmlPath);
//      AccountService accountService =  (AccountService) applicationContext.getBean("accountService");
        accountService.transfer("jack", "rose", 1000);
    }

}




<div class="se-preview-section-delimiter"></div>

6 整合web

6.1导入jar包

spring-web.xml

6.2 tomcat启动加载配置文件

servlet --> init(ServletConfig) --> <load-on-startup>2
filter --> init(FilterConfig)  --> web.xml注册过滤器自动调用初始化
listener --> ServletContextListener --> servletContext对象监听【】
spring提供监听器 ContextLoaderListener  --> web.xml  <listener><listener-class>....
    如果只配置监听器,默认加载xml位置:/WEB-INF/applicationContext.xml

6.3确定配置文件位置,通过系统初始化参数

ServletContext 初始化参数 web.xml

        <context-param>
            <param-name>contextConfigLocation
            <param-value>classpath:applicationContext.xml




<div class="se-preview-section-delimiter"></div>
  <!-- 确定配置文件位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <!-- 配置spring 监听器,加载xml配置文件 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>




<div class="se-preview-section-delimiter"></div>

6.4从servletContext作用域 获得spring容器 (了解)


// 从application作用域(ServletContext)获得spring容器
//方式1: 手动从作用域获取
ApplicationContext applicationContext = (ApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

//方式2:通过工具获取
ApplicationContext apppApplicationContext2 =WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());  

猜你喜欢

转载自blog.csdn.net/u011446177/article/details/79967602