• Spring(完整版)


    文章目录


    一、Spring

    (一)、Spring简介

    1、Spring概述

    官网地址:https://spring.io/
    可以理解为是一个管理者,管理的是整个分层架构中的每一个对象,将每一个对象称为JavaBean
    目的:Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO
    编程模型来促进良好的编程实践。
    Spring最主要学习的内容
    IOC:控制反转
    DI:依赖注入,DI有的前提是有IOC
    AOP:面向切面编程

    Spring 是最受欢迎的企业级 Java 应用程序开发框架,数以百万的来自世界各地的开发人员使用
    Spring 框架来创建性能好、易于测试、可重用的代码。
    Spring 框架是一个开源的 Java 平台,它最初是由 Rod Johnson 编写的,并且于 2003 年 6 月首
    次在 Apache 2.0 许可下发布。
    Spring 是轻量级的框架,其基础版本只有 2 MB 左右的大小。
    Spring 框架的核心特性是可以用于开发任何 Java 应用程序,但是在 Java EE 平台上构建 web 应
    用程序是需要扩展的。 Spring 框架的目标是使 J2EE 开发变得更容易使用,通过启用基于 POJO
    编程模型来促进良好的编程实践。

    2、Spring家族

    项目列表:https://spring.io/projects
    Spring下载jar包
    官网:https://spring.io/----->progects----->Spring Framework------点击猫头像-----找到Spring Framework Artifacts点击----- 找到Spring Artifactory点击-----找到libs-snapshot点击----org/------ Spring Framework/----spring/—选择需要的版本----
    或者直接输https://repo.spring.io/ui/native/libs-release-local/org/springframework/spring/5.0.6.RELEASE
    下载
    在这里插入图片描述

    3、Spring Framework

    Spring 基础框架,可以视为 Spring 基础设施,基本上任何其他 Spring 项目都是以 Spring Framework为基础的。

    1、Spring Framework五大功能模块

    在这里插入图片描述

    2、Spring Framework特性

    非侵入式: 使用 Spring Framework 开发应用程序时,Spring 对应用程序本身的结构影响非常小。对领域模型可以做到零污染;对功能性组件也只需要使用几个简单的注解进行标记,完全不会破坏原有结构,反而能将组件结构进一步简化。这就使得基于 Spring Framework 开发应用程序时结构清晰、简洁优雅。
    控制反转: IOC——Inversion of Control,翻转资源获取方向。把自己创建资源、向环境索取资源变成环境将资源准备好,我们享受资源注入。
    面向切面编程: AOP——Aspect Oriented Programming,在不修改源代码的基础上增强代码功能。
    容器: Spring IOC 是一个容器,因为它包含并且管理组件对象的生命周期。组件享受到了容器化的管理,替程序员屏蔽了组件创建过程中的大量细节,极大的降低了使用门槛,大幅度提高了开发效率。
    组件化: Spring 实现了使用简单的组件配置组合成一个复杂的应用。在 Spring 中可以使用 XML和 Java 注解组合这些对象。这使得我们可以基于一个个功能明确、边界清晰的组件有条不紊的搭建超大型复杂应用系统。
    声明式: 很多以前需要编写代码才能实现的功能,现在只需要声明需求即可由框架代为实现。
    一站式: 在 IOC 和 AOP 的基础上可以整合各种企业应用的开源框架和优秀的第三方类库。而且Spring 旗下的项目已经覆盖了广泛领域,很多方面的功能性需求可以在 Spring Framework 的基础上全部使用 Spring 来实现。

    (二)、控制反转IOC

    1、IOC容器

    1、IOC思想

    IOC:Inversion of Control,翻译过来是反转控制。
    ①获取资源的传统方式
    自己做饭:买菜、洗菜、择菜、改刀、炒菜,全过程参与,费时费力,必须清楚了解资源创建整个过程中的全部细节且熟练掌握。
    在应用程序中的组件需要获取资源时,传统的方式是组件主动的从容器中获取所需要的资源,在这样的模式下开发人员往往需要知道在具体容器中特定资源的获取方式,增加了学习成本,同时降低了开发效率。
    ②反转控制方式获取资源
    点外卖:下单、等、吃,省时省力,不必关心资源创建过程的所有细节。
    反转控制的思想完全颠覆了应用程序组件获取资源的传统方式:反转了资源的获取方向——改由容器主动的将资源推送给需要的组件,开发人员不需要知道容器是如何创建资源对象的,只需要提供接收资源的方式即可,极大的降低了学习成本,提高了开发的效率。这种行为也称为查找的被动形式。
    ③DI
    DI:Dependency Injection,翻译过来是依赖注入。
    DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。相对于IOC而言,这种表述更直接。所以结论是:IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。

    简单来说以前需要对象时自己new ,现在只需要提供接收资源的方式即可

    2、IOC容器在Spring中的两种实现方式

    Spring 的 IOC 容器就是 IOC 思想的一个落地的产品实现。IOC 容器中管理的组件也叫做 bean。在创建bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:

    BeanFactory

    这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。

    ②ApplicationContext

    BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用ApplicationContext 而不是底层的 BeanFactory。

    ③ApplicationContext的主要实现类

    Ctrl+H:可以查看当前接口或类 实现或继承的关系
    在这里插入图片描述

    类型名简介
    ClassPathXmlApplicationContext通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象(当前工程下获取)用的比较多
    FileSystemXmlApplicationContext通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象(从磁盘中获取)
    ConfigurableApplicationContexApplicationContext 的子接口,包含一些扩展方法refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。
    WebApplicationContext专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。

    2、基于XML管理bean

    1、搭建Spring环境
    ①创建Maven工程
    ②引入依赖
    <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.20version>
            dependency>
    
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    ③创建Spring的配置文件 ApplicationContext.xml

    idea中通过下面方式可直接创建:
    在这里插入图片描述
    如:

    
    <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">
      
      
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    ④在Spring的配置文件中配置bean

    配置HelloWorld类所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
    通过bean标签配置IOC容器所管理的bean

    bean: 将对象交给IOC容器管理
    bean的属性:
    id:bean的唯一标识,不能重复
    class:设置bean所对应类型的全类名

    
    <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="helloworld" class="com.cy.pojo.Hellow"/>
        
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    ⑤创建Bean工厂

    BeanFactory factory=new ClassPathXmlApplicationContext(“配置文件”);
    Object obj=(造型)factory.getBean(“配置文件中bean的name值”);
    在以上过程中,通过Spring的BeanFactory帮我们创建对象,将对象的控制权从自己new
    改变为跟Spring要----IOC控制反转
    如:

    package com.cy;
    
    import com.cy.pojo.Hellow;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class TestHello {
        @Test
        public void test() {
            //1、获取IOC容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
            //2、获取IOC容器中的bean
            Hellow hellow = (Hellow) ac.getBean("helloworld");
            hellow.sayHello();
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    ⑥注意Spring 底层

    Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name
    ‘helloworld’ defined in class path resource [applicationContext.xml]: Instantiation of bean
    failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed
    to instantiate [com.cy.pojo.HelloWorld]: No default constructor found; nestedexception is java.lang.NoSuchMethodException: com.cy.pojo.HelloWorld.<《init>()

    ⑦获取IOC容器的方式

    1.Spring管理的对象有多少个
    每一个数据库的表格会对应一套Controller Service Dao
    如果有10个表格则有10个C 10个S 10个D,所以管理的对象有很多个,分属在不同的层次中,我们可以将配置拆分
    将xml文件拆分:
    方式一:(String动态参数)
    ClassPathXmlApplicationContext(“ApplicationContext.xml”,” ”,” ”);
    方式二:String数据
    ClassPathXmlApplicationContext(new String[]{“ApplicationContext.xml”,” ”,” ”});
    方式三:统配符写法*
    ClassPathXmlApplicationContext(“ApplicationContext*.xml”);
    方式四:主配置文件引入其他文件的方式
    ClassPathXmlApplicationContext(“ApplicationContext.xml”);
    在ApplicationContext.xml文件中引入,通过:import

     <import resource=”ApplicationContext_dao.xml”>import>
    
    • 1
    2、获取bean的几种方式

    案例:
    applicationContext.xml文件

    
    <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="studentOne" class="com.cy.pojo.Student"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    实体类文件

    package com.cy.pojo;
    import lombok.Data;
    @Data
    public class Student {
        private Integer sid;
        private String sname;
        private Integer age;
        private String gender;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    ①方式一:根据id获取

    由于 id 属性指定了 bean 的唯一标识,所以根据 bean 标签的 id 属性可以精确获取到一个组件对象。上个实验中我们使用的就是这种方式。

    package com.cy.test;
    
    import com.cy.pojo.Student;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class IocByXMLTest {
        @Test
        public  void testIOC(){
            //获取iOC容器
            ApplicationContext ioc=new ClassPathXmlApplicationContext("applicationContext.xml");
            //获取bean
            Student student=(Student) ioc.getBean("studentOne");
            System.out.println(student);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    ②方式二:根据类型获取
    @Test
    public void testHelloWorld(){
    	ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
    	HelloWorld bean = ac.getBean(Student.class);
    	bean.sayHello();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    注意
    当根据类型获取bean时,要求IOC容器中指定类型的bean有且只能有一个
    当IOC容器中一共配置了两个:

      <bean id="studentOne" class="com.cy.pojo.Student"/>
      <bean id="studentTwo" class="com.cy.pojo.Student"/>
    
    • 1
    • 2

    根据类型获取时会抛出异常:

    org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean
    of type ‘com.cy.pojo.Student’ available: expected single matching bean but
    found 2: studentOne,studentTwo

    ③方式三:根据id和类型获取
    @Test
    public void testHelloWorld(){
    	ApplicationContext ac =  newClassPathXmlApplicationContext("applicationContext.xml");
    	HelloWorld bean = ac.getBean("studentOne", Student.class);
    	bean.sayHello();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    ④扩展

    1、如果组件类实现了接口,根据接口类型可以获取 bean 吗?
    可以,前提是bean唯一
    2、如果一个接口有多个实现类,这些实现类都配置了 bean,根据接口类型可以获取 bean 吗?
    不行,因为bean不唯一

    ⑤结论

    根据类型来获取bean时,在满足bean唯一性的前提下,其实只是看:『对象 instanceof 指定的类
    型』的返回结果,只要返回的是true就可以认定为和类型匹配,能够获取到。

    3、依赖注入(DI)的几种方式

    对象创建的同时能自动的将对象中的属性值注入进去---- DI依赖注入
    通过bean创建的同时给属性赋值

    方式一:依赖注入之setter注入
    1、set注入的写法
    <bean name=”和getBean的参数一致” class=”需要创建对象的类全名”>
    	
    	<property name=”属性名” value=”属性值”>property>
    	
    	<property name="属性名">
             <value type="属性类型">属性值value>
         property>
    bean>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    注意: 用set方法赋值时,无参数构造方法和属性对应的set方法必须存在
    如:

    
    <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="studentTwo" class="com.cy.pojo.Student">
            
            
            <property name="sid" value="1"/>
            
            <property name="age">
                <value type="java.lang.Integer">18value>
            property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    2、用set方法赋值的genBean底层:
        1.读取xml文件----得到class(domain.Student)类
        2.Class clazz=Class.forName("domain.Student");
        3.Student studnet=(Student)clazz.newInstance();
        4.找寻class中的所有私有属性  filed() fs=clazz.getFields();
        5.for(fs){
            属性类型 getType
            属性名字 getName  处理set方法名 set+大写+属性名后半部分
            属性找到对应的set方法进行赋值
            set.invode();   
             }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    方式二:依赖注入之构造器注入
    1、构造器注入的写法

    constructor-arg标签还有两个属性可以进一步描述构造器参数:
    index属性:指定参数所在位置的索引(从0开始)
    name属性:指定参数名(属性名)
    value属性:属性值
    type属性:属性类型
    ref属性:关联对象bean的name值(别的类做为属性时用)

    <bean name=”和getBean的参数一致” class=”需要创建对象的类全名”>
    	
    	<constructor-arg name="属性名" value="属性值" type="属性类型" />
    	 
    	<constructor-arg name="属性名" type=”属性类型”>
    	    <value>属性值value>
    	constructor-arg>
    bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    注意:用构造方法注入时,
    1、constructor-arg的个数一定要和有参构造中参数的的个数一致,否则class报错
    2、有参构造方法必须存在
    如:

    
    <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="studentOne" class="com.cy.pojo.Student">
            
            
            <constructor-arg name="sid" value="2" type="java.lang.Integer"/>
            <constructor-arg name="age" value="1" type="java.lang.Integer"/>
            <constructor-arg name="gender" value="" type="java.lang.String"/>
            
            <constructor-arg name="sname" type="java.lang.String">
                <value>张三value>
            constructor-arg>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    2、用构造方法给属性赋值的getBean的底层
        1.创建bean工厂 读取xml文件  class类名字
        2.class  clazz=Class.forName(类名字)
        3.找到带参数的构造方法 Constructor con=clazz.getConstructor(参数)
          配置决定参数个数,配置还决定是否能与属性匹配,如果匹配则通过反射找到那个属性
        4.执行构造方法创建对象 con.newInstance(值)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    4、特殊值赋值处理
    ①字面量赋值

    什么是字面量?
    int a = 10;
    声明一个变量a,初始化为10,此时a就不代表字母a了,而是作为一个变量的名字。当我们引用a
    的时候,我们实际上拿到的值是10。而如果a是带引号的:‘a’,那么它现在不是一个变量,它就是代表a这个字母本身,这就是字面量。所以字面量没有引申含义,就是我们看到的这个数据本身。

    
    <property name="name" value="张三"/>
    
    • 1
    • 2
    ②null值

    如果某一个属性中需要赋值空对象,null对象,而非是空字符串“null“,

    <property name="name">
    	<null />
    property>
    
    • 1
    • 2
    • 3

    注意:

    <property name="name" value="null">property>
    
    • 1

    以上写法,为name所赋的值是字符串null

    ③特殊字符
    	
    	
    	<property name="expression" value="a < b"/>
    	
    	<property name="expression">
    		
    		
    		
    		
    		<value>value>
    	property>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    5、为类类型属性赋值

    对象里面的属性有对象类型
    student类

    package com.cy.pojo;
    
    import lombok.*;
    
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class Student {
        private Integer sid;
        private String sname;
        private Integer age;
        private String gender;
        private Clazz clazz;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    方法一:引用外部已声明的bean


    内部bean只能用于给属性赋值,不能在外部通过IOC容器获取,因此可以省略id属性
    如:
    applicationContext.xml文件:

    
    <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="clazzOne" class="com.cy.pojo.Clazz">
            <property name="cid" value="1"/>
            <property name="cname" value="一班"/>
        bean>
        
        <bean id="studentTree" class="com.cy.pojo.Student">
            <property name="sid" value="5"/>
            <property name="sname" value="赵六"/>
            
            <property name="clazz" ref="clazzOne"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    方法二:内部bean

    引用外部已声明的bean在外面可以通过getBean获取到Clazz对象,如果想要获取不到,则可以采用内部bean的方式,相当与私有属性
    如:

    
    <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="studentFour" class="com.cy.pojo.Student">
            <property name="sid" value="1004"/>
            <property name="sname" value="赵六"/>
            <property name="age" value="26"/>
            <property name="gender" value=""/>
            <property name="clazz">
                
                
                <bean class="com.cy.pojo.Clazz">
                    <property name="cid" value="2222"/>
                    <property name="cname" value="远大前程班"/>
                bean>
            property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    方法三:级联属性赋值

    一定先引用某个bean为属性赋值,才可以使用级联方式更新属性

    
    <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="studentFour" class="com.cy.pojo.Student">
            <property name="sid" value="1004"/>
            <property name="sname" value="赵六"/>
            <property name="age" value="26"/>
            <property name="gender" value=""/>
            
            <property name="clazz" ref="clazzOne"/>
            <property name="clazz.cid" value="3333"/>
            <property name="clazz.cname" value="最强王者班"/>
        bean>
        
        <bean id="clazzOne" class="com.cy.pojo.Clazz">
            <property name="cid" value="1"/>
            <property name="cname" value="一班"/>
        bean>
    
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    6、为数组类型属性赋值
    <constructor-arg name="数组属性名" >
             <array value-type="java.lang.String" >  //value-type为数组的类型
                 <value type="java.lang.String">aaavalue>  //数组的值 type为值的类型
             array>
    constructor-arg>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如:

    
    <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="clazzOne" class="com.cy.pojo.Clazz">
            <property name="cid" value="1"/>
            <property name="cname" value="一班"/>
        bean>
        
        < <bean id="studentFour" class="com.cy.pojo.Student">
            <property name="sid" value="1004"/>
            <property name="sname" value="赵六"/>
            <property name="age" value="26"/>
            <property name="gender" value=""/>
            
            <property name="clazz" ref="clazzOne"/>
            <property name="hobbys">
                <array>
                    <value>抽烟value>
                    <value>喝酒value>
                    <value>烫头value>
                array>
            property>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    如果数组中的值是对象类型的则:

    	<constructor-arg name="array" >
           <array > //value-type为数组的类型
             <bean Class=”对象的类全名”>bean> 
           array>
    	constructor-arg><bean id=”bean1” class=”对象的类全名” >bean>
    	<constructor-arg name="array" >
    	       <array > 
    	        	<ref bean=”bean1”>ref>
    	       array>
    	constructor-arg>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    7、为集合类型属性赋值
    ①为List集合类型属性赋值
    	<constructor-arg name="属性名" >
             <list value-type="java.util.list ">//value-type为集合的类型
                 <value type="java.lang.String">aaavalue>//集合的值 type为值的类型
             list>
    	constructor-arg>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如果集合中的值是对象类型的则:

    	<constructor-arg name="属性名" >
           <list >//value-type为集合的类型
              <bean Class=”对象的类名”>bean> 
           list>
    	constructor-arg><bean id=”bean1” class=”对象的类名” >bean>
    	<constructor-arg name="属性名" >
    	       		<list> 
    	        		<ref bean=”bean1”>ref>
    	      		list>
    	constructor-arg>
    	或:
    	 
        <util:list id="studentList">
            <ref bean="studentOne">ref>
            <ref bean="studentTwo">ref>
        util:list>
        <bean id="clazzTwo" class="com.cy.pojo.Clazz">
            <property name="cid" value="4444">property>
            <property name="cname" value="Javaee0222">property>
            <property name="studentList" ref="studentList"/>
        bean>
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    若为Set集合类型属性赋值,只需要将其中的list标签改为set标签即可

    
    <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="studentOne" class="com.cy.pojo.Student">
            <property name="sid" value="1"/>
            <property name="sname" value="张三"/>
        bean>
        <bean id="studentTwo" class="com.cy.pojo.Student">
            <property name="sid" value="2"/>
            <property name="sname" value="李四"/>
        bean>
        <bean id="clazzTwo" class="com.cy.pojo.Clazz">
            <property name="cid" value="4444">property>
            <property name="cname" value="Javaee0222">property>
            <property name="studentList">
                <list>
                    <ref bean="studentOne">ref>
                    <ref bean="studentTwo">ref>
                list>
            property>
        bean>
        
        
        
        <util:list id="studentList">
            <ref bean="studentOne">ref>
            <ref bean="studentTwo">ref>
        util:list>
        <bean id="clazzTwo" class="com.cy.pojo.Clazz">
            <property name="cid" value="4444">property>
            <property name="cname" value="Javaee0222">property>
            <property name="studentList" ref="studentList"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    ②为Map集合类型属性赋值

    Map集合的注入

    	<property name="属性名">
                <map key-type="java.lang.Integer" value-type="java.lang.String">
                    <entry key="1" value="aaa">entry>//集合中的值
                map>
    	property>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    如果map集合中对象类型,则

    	<property name="属性名">
                <map key-type="key的类型" value-type="value类型 ">
                    <entry>//集合中的一个元素
    					<key>key的值key>
    					<bean class=”对象的类”>bean>//value的值
    				entry> 
    				<entry key-ref="" value-ref=""/>
                map>
    	property>
    	或将
    	<bean name=”” class=”对象的类”>bean>写在外面,加上name属性,用
    	<entry key=”key” value-ref=”bean的name”>entry>
    	注入Properties对象,Propertiest的本质是map集合
    	<bean name="properties" class="domain.PropertiesTest">
            <constructor-arg name="properties">
                <props>
                    <prop key="1">888prop>
                props>
            constructor-arg> 
        bean> 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    注意:在配置文件中,若两种方式都给同一对象进行赋值,则最终按照set方法的值作为最终的结果,因为构造方法是先执行的

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xmlns:util="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
       
        
        
        <bean id="studentFour" class="com.cy.pojo.Student">
            <property name="sid" value="1004"/>
            <property name="sname" value="赵六"/>
            <property name="age" value="26"/>
            <property name="gender" value=""/>
            
            <property name="clazz" ref="clazzOne"/>
            <property name="hobbys">
                <array>
                    <value>抽烟value>
                    <value>喝酒value>
                    <value>烫头value>
                array>
            property>
            <property name="teacherMap">
                <map>
                    <entry key="10010" value-ref="teacherOne"/>
                    <entry>
                        <key>
                            <value>10086value>
                        key>
                        <ref bean="teacherTwo">ref>
                    entry>
                map>
            property>
        bean>
        <bean id="teacherOne" class="com.cy.pojo.Teacher">
            <property name="tid" value="1"/>
            <property name="tname" value="张老师"/>
        bean>
        <bean id="teacherTwo" class="com.cy.pojo.Teacher">
            <property name="tid" value="1"/>
            <property name="tname" value="王老师"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57

    使用util:list、util:map标签必须引入相应的命名空间,可以通过idea的提示功能选择

    8、p命名空间

    在标签配置过程中,为了简便配置文件的写法,Spring提供了p命名空间,
    命名空间问题

    Property P:属性名=“值“
    Constructor-arg c:属性名=“值“

    有了这种命名空间规范后,可以将原来嵌套在bean标签中的两个属性,放在bean标签中
    但要在配置文件的头部导入要给规则:

    xmlns:c="http://www.springframework.org/schema/c
    xmlns:p="http://www.springframework.org/schema/p

    可以用c:属性名=”值“
    如果是基本类型。用c:属性名=”值“
    如果是对象类型,则用c:属性名-ref=”属性bean对象的name“

    引入p命名空间后,可以通过以下方式为bean的各个属性赋值

    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
           xmlns:util="http://www.springframework.org/schema/c"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        
        <bean id="studentSix" class="com.cy.pojo.Student" p:sid="1" p:clazz-ref="clazzOne"/>
        
        
        <bean id="clazzOne" class="com.cy.pojo.Clazz">
            <property name="cid" value="1"/>
            <property name="cname" value="一班"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    9、引入外部属性文件

    在Spring的核心文件中引入外部文件,通常外部文件为.properties,通过context引入一个外部的properties文件, 通过${}获取properties文件中的值
    如:
    Properties文件中的内容
    name=thinpag

    applicationContext.xml文件中:

    	
    	<context:property-placeholder  location="properties文件的名"/>
        
        <bean id="" class="类全名">
            <property name="属性" value="${name}"/>
        bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    案例:引入jdbc.properties文件
    ①加入依赖

    <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.20version>
            dependency>
    
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <version>RELEASEversion>
                <scope>compilescope>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.16version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.0.31version>
            dependency>
        dependencies>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    ②创建jdbc.properties文件

    jdbc.driver=com.mysql.cj.jdbc.Driver
    jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC
    jdbc.username=root
    jdbc.password=123456
    
    • 1
    • 2
    • 3
    • 4

    ③引入属性文件并配置bean

    
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
        
        <context:property-placeholder location="classpath:jdbc.properties"/>
        
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="${jdbc.url}"/>
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    10、bean的加载机制(bean的作用域)

    Spring管理的bean对象默认的效果是单例模式,单例模式底层是:生命周期托管的方式,单例模式可以修改
    在ApplicationContext.xml中的中加scope属性
    Scope=”singleton只要name一致就是单例/prototype原型每次new新的”
    如果采用的是默认单例模式singleton,bean在IOC容器中只有一个实例,IOC容器初始化时创建对象 是立即加载的(表示获取bean所对应的对象都是同一个)
    如果采用的是原型模式prototype,bean在IOC容器中可以有多个实例,getBean()时创建对象(表示获取bean所对应的对象都不是同一个)

    我们开发的时候可能更多的使用延迟加载的机制,所以可以通过修改Spring配置的方式来改变

    <bean name="student" class="domain.Student" scope="singleton" Lazy-init="true">bean>
    
    • 1

    Lazy-init=”default/false表示立即加载 true表示延迟加载”
    概念:
    在Spring中可以通过配置bean标签的scope属性来指定bean的作用域范围,各取值含义参加下表:
    在这里插入图片描述

    11、bean的生命周期
    ①具体的生命周期过程
    • bean对象创建(调用无参构造器)
    • 给bean对象设置属性
    • bean对象初始化之前操作(由bean的后置处理器负责)
    • bean对象初始化(需在配置bean时指定初始化方法)
    • bean对象初始化之后操作(由bean的后置处理器负责)
    • bean对象就绪可以使用
    • bean对象销毁(需在配置bean时指定销毁方法)
    • IOC容器关闭

    注意: ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法

    Bean标签中还有两个属性:
    init-method=“xxx方法名”:表示初始化时调用xxx方法
    destroy-method=”xxx方法名”:表示销毁时调用xxx方法
    方法initMethod()和destroyMethod(),可以通过配置bean指定为初始化和销毁的方法

    ②bean的作用域对生命周期的影响:
        若bean的作用域为多例时,生命周期的前三个步骤会在获取bean时执行
        若bean的作用域为单例时,生命周期的前三个步骤会在获取IOC容器时执行
    
    • 1
    • 2
    ③bean的前置和后置处理器

    bean的后置处理器会在生命周期的初始化前后添加额外的操作,需要实现BeanPostProcessor接口,且配置到IOC容器中,需要注意的是,bean后置处理器不是单独针对某一个bean生效,而是针对IOC容器中所有bean都会执行
    创建bean的后置处理器:

    package com.cy.process;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class MyBeanProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            //此方法在bean的生命周期初始化之前执行
            System.out.println("bean的后置处理器的前置postProcessBeforeInitialization");
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            //此方法在bean的生命周期初始化之后执行
            System.out.println("bean的后置处理器的后置postProcessAfterInitialization");
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    在IOC容器中配置后置处理器:

    
    <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 class="com.cy.pojo.User" scope="prototype" init-method="initMethod"
              destroy-method="destroyMethod">
            <property name="id" value="1001">property>
            <property name="username" value="admin">property>
            <property name="password" value="123456">property>
            <property name="age" value="23">property>
        bean>
        
        
        <bean id="myBeanProcessor" class="com.cy.process.MyBeanProcessor"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    ④验证bean生命周期的方法

    user类:

    package com.cy.pojo;
    
    public class User {
        private Integer id;
        private String username;
        private String password;
        private Integer age;
        public User() {
            System.out.println("生命周期:1、创建对象");
        }
        public User(Integer id, String username, String password, Integer age) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.age = age;
        }
        public Integer getId() {
            return id;
        }
        public void setId(Integer id) {
            System.out.println("生命周期:2、依赖注入");
            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;
        }
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        public void initMethod(){
            System.out.println("生命周期:3、初始化");
        }
        public void destroyMethod(){
            System.out.println("生命周期:5、销毁");
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    创建bean的后置处理器:

    package com.cy.process;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanPostProcessor;
    
    public class MyBeanProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
            //此方法在bean的生命周期初始化之前执行
            System.out.println("bean的后置处理器的前置postProcessBeforeInitialization");
            return bean;
        }
    
        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
            //此方法在bean的生命周期初始化之后执行
            System.out.println("bean的后置处理器的后置postProcessAfterInitialization");
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    bean的配置文件:

    
    <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 class="com.cy.pojo.User" scope="prototype" init-method="initMethod"
              destroy-method="destroyMethod">
            <property name="id" value="1001">property>
            <property name="username" value="admin">property>
            <property name="password" value="123456">property>
            <property name="age" value="23">property>
        bean>
        
        <bean id="myBeanProcessor" class="com.cy.process.MyBeanProcessor"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    测试类:

    package com.cy.test;
    
    import com.cy.pojo.Student;
    import com.cy.pojo.User;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    
    import javax.sql.DataSource;
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public class IocByXMLTest {
      /***注意:** ConfigurableApplicationContext是ApplicationContext的子接口,其中扩展了刷新和关闭容器的方法*/
        @Test
        public void testLife(){
            ClassPathXmlApplicationContext ac = new
                    ClassPathXmlApplicationContext("spring-lifecycle.xml");
            User bean = ac.getBean(User.class);
            System.out.println("生命周期:4、通过IOC容器获取bean并使用");
            ac.close();
        }
         /*结果如下:
        生命周期:1、创建对象
    	生命周期:2、依赖注入
    	生命周期:3、bean的后置处理器的前置postProcessBeforeInitialization
    	生命周期:4、初始化
    	生命周期:5、bean的后置处理器的后置postProcessAfterInitialization
    	生命周期:6、通过IOC容器获取bean并使用*/
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    12、FactoryBean
    ①简介

    FactoryBean是Spring提供的一种整合第三方框架的常用机制。和普通的bean不同,配置一个FactoryBean类型的bean,在获取bean的时候得到的并不是class属性中配置的这个类的对象,而是getObject()方法的返回值。通过这种机制,Spring可以帮我们把复杂组件创建的详细过程和繁琐细节都屏蔽起来,只把最简洁的使用界面展示给我们。
    将来我们整合Mybatis时,Spring就是通过FactoryBean机制来帮我们创建SqlSessionFactory对象的。

    FactoryBean是一个接口,需要创建一个类实现该接口
    其中有三个方法:
    getObject():通过一个对象交给IOC容器管理
    getObjectType():设置所提供对象的类型
    isSingLeton():所提供的对象是否单例
    当把FactoryBean的实现类配置为bean是,会将当前类中getObject()所返回的对象交给IOC容器管理

    ②用法

    创建类UserFactoryBean:

    package com.cy.pojo;
    
    import org.springframework.beans.factory.FactoryBean;
    
    public class UserFactoryBean implements FactoryBean<User> {
        @Override
        public User getObject() throws Exception {
            return new User();
        }
    
        @Override
        public Class<?> getObjectType() {
            return User.class;
        }
    
        @Override
        public boolean isSingleton() {
            return false;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    配置spring配置文件:

    
    <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="myuserFactoryBean" class="com.cy.pojo.UserFactoryBean"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    测试:

    package com.cy.test;
    import com.cy.pojo.User;
    import org.junit.Test;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class IocByXMLTest {
    
    
        /**
         * FactoryBean是一个接口,需要创建一个类实现该接口
         * 其中有三个方法:
         *      getObject():通过一个对象交给IOC容器管理
         *      getObjectType():设置所提供对象的类型
         *      isSingLeton():所提供的对象是否单例
         * 当把FactoryBean的实现类配置为bean是,会将当前类中getObject()所返回的对象交给IOC容器管理
         */
        @Test
        public void testUserFactoryBean(){
            //获取IOC容器
            ApplicationContext ac = new ClassPathXmlApplicationContext("spring-factory.xml");
            User user = (User) ac.getBean("user");
            System.out.println(user);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    13、基于xml的自动装配
    1、手动装配的方式
    
    <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="userController" class="com.cy.controller.UserController">
            <property name="userServiceImp" ref="serviceImp"/>
        bean>
        <bean id="serviceImp" class="com.cy.service.UserServiceImp">
            <property name="userDao" ref="userDao"/>
        bean>
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
        
        <bean id="userController" class="com.cy.controller.UserController">
            <constructor-arg name="userServiceImp">
                <bean name="userServiceImp" class="com.cy.service.UserServiceImp">
                    <constructor-arg name="userDao">
                        <bean id="userDao2" class="com.cy.dao.UserDaoImpl"/>
                    constructor-arg>
                bean>
            constructor-arg>
        bean>
        
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    2、自动装配的方式:

    根据指定的策略,在IOC容器中匹配某一个bean,自动为指定的bean中所依赖的类类型或接口类型属性赋值
    对象的自动注入:
    1.构造方法自动注入

    	<bean name="controller" class="com.cy.controller.UserController" autowire="constructor"/>
        <bean id="userService" class="com.cy.service.UserServiceImp" autowire="constructor"/>
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
    
    • 1
    • 2
    • 3

    2.Set方法自动注入

    <bean name="service" class="service.StudentService" autowire="byName/byType"/>
    
    • 1

    可以根据bean标签中的autowire属性设置自动装配的策略
    可以自动装配的策略:
    1、no,defalut:表示不装配,即bean中的属性不会自动匹配某个bean为属性值,
    此时属性使用默认值
    2、 byType:根据要赋值的属性的类型,在IOC容器中自动匹配某个bean,为属性赋值(即bean对象中的属性类型与另一个bean对象的class类型一致即可自动匹配)
    注意:
    (1)、若在IOC中,没有任何一个兼容类型的bean能够为属性赋值,则该属性不装配,即值为默认值null
    (2)、若在IOC中,有多个兼容类型的bean能够为属性赋值,则抛出异常NoUniqueBeanDefinitionException
    3、 byName:将自动装配的属性的属性名,作为bean的id在IOC容器中匹配相对应的bean进行赋值(即bean对象中的属性名与另一个bean对象的name/id一致即可自动注入)
    总结:当时用byType实现自动装配是,IOC容器中有且只有一个类型匹配的bean能够为属性赋值,当类型匹配的bean有多个时,此时可以使用byName实现自动装配

    
    <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="userController" class="com.cy.controller.UserController" autowire="byType"/>
        <bean id="userService" class="com.cy.service.UserServiceImp" autowire="byType"/>
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
        
        
        <bean id="userController" class="com.cy.controller.UserController" autowire="byName">
           
        bean>
        <bean id="serviceImp" class="com.cy.service.UserServiceImp" autowire="byName">
           
        bean>
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
        
    	 
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
        <bean name="controller" class="com.cy.controller.UserController" autowire="constructor"/>
        <bean id="userService" class="com.cy.service.UserServiceImp" autowire="constructor"/>
        <bean id="userDao" class="com.cy.dao.UserDaoImpl"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37

    注意:
    如果对象中的属性是抽象类、接口类型,属性是没有办法直接创建对象赋值,属性赋值一定是子类(不止一个可以啦)
    a、利用是构造方法方式自动装配先按照类型匹配
    刚好一个就直接赋值如果类型发现不止一个对应
    再按照属性名与bean的name或id匹配 ,成功匹配 就赋值
    b、利用无参数构造方法+set方法进行自动装配
    byName形式 按照名字进行找寻 ,找不到就没有找到就装配
    byType形式 如果有两个以上对应的类型 标签配置时直接报错 采用内部形式ref自己指定的形式
    在这里插入图片描述

    3、基于注解管理bean

    1、标记与扫描

    ①注解
    和 XML 配置文件一样,注解本身并不能执行,注解本身仅仅只是做一个标记,具体的功能是框架检测到注解标记的位置,然后针对这个位置按照注解标记的功能来执行具体操作。
    本质上: 所有一切的操作都是Java代码来完成的,XML和注解只是告诉框架中的Java代码如何执行
    举例: 元旦联欢会要布置教室,蓝色的地方贴上元旦快乐四个字,红色的地方贴上拉花,黄色的地方贴
    上气球。班长做了所有标记,同学们来完成具体工作。墙上的标记相当于我们在代码中使用的注解,后面同学们
    做的工作,相当于框架的具体操作。
    ②扫描
    Spring 为了知道程序员在哪些地方标记了什么注解,就需要通过扫描的方式,来进行检测。然后根据注解进行后续操作。

    2、标识组件的常用注解

    Spring的注解,用于替代bean标签的作用,让Spring帮我们管理一个对象,Spring主要的是对于对象的管理 IOC DI,想要将某一个类交给Spring来进行管理,可以在类上面写一个万能直@Component
    @Component(value=”id”) 如果value写,默认的值是“” 但是肯定不能用这个“”作为id,所以如果不写的话,对象的获取通过类名的驼峰命名法
    @Component注解的可读性不强,让用户更加能体现出分层,所以Spring提供了一下的注解:

    • @Component:将类标识为普通组件
    • @Controller:将类标识为控制层组件 controller层
    • @Service:将类标识为业务层组件 service层
    • @Repository:将类标识为持久层组件 dao层
    1、以上四个注解有什么关系和区别?

    在这里插入图片描述
    通过查看源码我们得知,@Controller、@Service、@Repository这三个注解只是在@Component注解的基础上起了三个新的名字。对于Spring使用IOC容器管理这些组件来说没有区别。所以@Controller、@Service、@Repository这
    三个注解只是给开发人员看的,让我们能够便于分辨组件的作用。
    注意:虽然它们本质上一样,但是为了代码的可读性,为了程序结构严谨我们肯定不能随便胡乱标记。

    3、扫描组件的方式
    方式一:最基本的扫描方式
    	
        <context:component-scan base-package="com.cy"/>
    
    • 1
    • 2
    方式二:指定要排除的组件

    context:exclude-filter标签:指定排除扫描规则
    type:设置排除扫描的方式
    type=“annotation”,根据注解排除,expression中设置要排除的注解的全类名
    type=“assignable”,根据类的类型排除,expression中设置要排除的类型的全类名

    
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
        
        
        <context:component-scan base-package="com.cy">
            
            
            
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            
            <context:exclude-filter type="assignable" expression="com.cy.controller.UserController"/>
        context:component-scan>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    方式三:仅扫描指定组件

    context:include-filter标签:指定在扫描所有类的基础上只扫描那个(包含扫描)
    注意:需要在context:component-scan标签中设置use-default-filters=“false”
    use-default-filters=“false”:所设置的包下所有的类都不需要扫描,此时可以使用包含扫描
    use-default-filters=“true”:所设置的包下所有的类都需要扫描,此时可以使用排除扫描
    type:设置排除或包含的依据
    type=“annotation”,根据注解排除,expression中设置要排除的注解的全类名
    type=“assignable”,根据类的类型排除,expression中设置要排除的类型的全类名

    
    <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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    
    
            
        <context:component-scan base-package="com.cy" use-default-filters="false">
            
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:include-filter type="assignable" expression="com.cy.controller.UserController"/>
        context:component-scan>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    4、组件所对应的bean的id

    在我们使用XML方式管理bean的时候,每个bean都有一个唯一标识,便于在其地方引用。现在使用注解后,每个组件仍然应该有一个唯一标识。

    1、注解+扫描配置id的默认情况
    类名首字母小写就是bean的id。例如:UserController类对应的bean的id就是userController。
    2、自定义bean的id
    可通过标识组件的注解的value属性设置自定义的bean的id
    @Service(“userService”)//默认为userServiceImpl
    public class UserServiceImpl implementsUserService {}

    5、基于注解的自动装配

    如果属性是对象,则用@Autowired对对象中的属性进行自动注入,可以方法set方
    法和构造方法的上面,还可以将注解放置在属性的上面
    底层通过反射直接操作私有属性进行赋值

    Class clazz=Class.forName(“类名”);
    Field[] fields=Clazz.getFields();//获取属性
    String fieldName=fields[0].getName;//获取属性名
    String setName=”set”+fieldName处理;
    Fields[0].setAccessable(true); fields[0].set(obj.value)

    如果属性是值,则用@Value(值)用来做固定值注入,放置在属性上面
    @Qualifier来实现一个对象注入的微调整,但要配合@Autowired使用
    当注入的对象不止一个的时候,可以通过次注解来进行指定@Qualifier(“要注入的id”)
    @Resource注解和@Autowired和@Qualifier作用一样,但他不是Spring家族的注
    解,统一管理显得不方便,所以看情况使用

    ①场景模拟

    参考基于xml的自动装配
    在UserController中声明UserService对象
    在UserServiceImpl中声明UserDao对象

    ②@Autowired注解

    @Autowired注解即可完成自动装配,不需要提供setXxx()方法。以后我们在项目中的正式用法就是这样。

    @Controller
    public class UserController {
    	@Autowired
    	private UserService userService;
    	
    	public void saveUser(){
    		userService.saveUser();
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    ③@Autowired注解其他细节

    @Autowired可以标记的位置:
    1、在成员变量上直接标记
    2、@Autowired注解可以标记在构造器和set方法上

    @Controller
    public class UserController {
    	private UserService userService;
    	
    	@Autowired
    	public UserController(UserService userService){
    		this.userService = userService;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    ④@Autowired的工作流程

    在这里插入图片描述
    首先根据所需要的组件类型到IOC容器中查找
    能够找到唯一的bean:直接执行装配
    如果完全找不到匹配这个类型的bean:装配失败
    和所需类型匹配的bean不止一个
    1、没有@Qualifier注解:根据@Autowired标记位置成员变量的变量名作为bean的id进行
    匹配
    能够找到:执行装配
    找不到:装配失败
    2、使用@Qualifier注解:根据@Qualifier注解中指定的名称作为bean的id进行匹配
    能够找到:执行装配
    找不到:装配失败

    @Autowired中有属性required,默认值为true,因此在自动装配无法找到相应的bean时,会装
    配失败
    可以将属性required的值设置为true,则表示能装就装,装不上就不装,此时自动装配的属性为
    默认值
    但是实际开发时,基本上所有需要装配组件的地方都是必须装配的,用不上这个属性。

    @Autowired注解原理
    1、默认通过byType的方式,在IOC容器中通过类型匹配某个bean为属性赋值
    2、若有多个类型匹配的bean,此时会自动转换为byName的方式实现自动装配的效果
    即将要赋值的属性的属性名作为bean的id匹配某个bean为属性赋值
    3、若byType和byName的方式都无妨实现自动装配,即IOC容器中有多个类型匹配的bean,
    且这些bean的id和要赋值的属性的属性名都不一致,此时抛出异常:NoUniqueBeanDefinitionException
    4、此时可以在要赋值的属性上,添加一个注解@Qualifier,通过该注解的value属性值,指定某个bean的id,将这个bean为属性赋值

    (三)、代理模式

    1、场景模拟

    package com.cy.controller;
    
    public class Calculator {
    
        public int sub(int i, int j) {
            System.out.println("[日志] sub 方法开始了,参数是:" + i + "," + j);
            int result = i - j;
            System.out.println("方法内部 result = " + result);
            System.out.println("[日志] sub 方法结束了,结果是:" + result);
            return result;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、提出问题

    ①现有代码缺陷

    针对带日志功能的实现类,我们发现有如下缺陷:

    • 对核心业务功能有干扰,导致程序员在开发核心业务功能时分散了精力
    • 附加功能分散在各个业务功能方法中,不利于统一维护
    ②解决思路

    解决这两个问题,核心就是:解耦。我们需要把附加功能从业务功能代码中抽取出来。

    ③困难

    解决问题的困难:要抽取的代码在方法内部,靠以前把子类中的重复代码抽取到父类的方式没法解决。
    所以需要引入新的技术。

    3、静态代理和动态代理

    1、概念
    ①介绍

    二十三种设计模式中的一种,属于结构型模式。它的作用就是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接对目标方法进行调用,而是通过代理类间接调用。让不属于目标方法核心逻辑的代码从目标方法中剥离出来——解耦。调用目标方法时先调用代理对象的方法,减少对目标方法的调用和打扰,同时让附加功能能够集中在一起也有利于统一维护。
    在这里插入图片描述

    ②生活中的代理

    广告商找大明星拍广告需要经过经纪人
    合作伙伴找大老板谈合作要约见面时间需要经过秘书
    房产中介是买卖双方的代理

    ③相关术语

    代理:将非核心逻辑剥离出来以后,封装这些非核心逻辑的类、对象、方法。
    目标:被代理“套用”了非核心逻辑代码的类、对象、方法。

    2、静态代理

    可以理解为代理知道自己代理的是谁,因为代理类中存储一个真实对象作为属性,可以认为代理的是对象
    体现: ORM的封装
    静态代理流程图:
    在这里插入图片描述
    例如:
    创建静态代理类:

    public class CalculatorStaticProxy implements Calculator {
    	// 将被代理的目标对象声明为成员变量
    	private Calculator target;
    	public CalculatorStaticProxy(Calculator target) {
    		this.target = target;
    	}
    	@Override
    	public int add(int i, int j) {
    		// 附加功能由代理类中的代理方法来实现
    		System.out.println("[日志] add 方法开始了,参数是:" + i + "," + j);
    		// 通过目标对象来实现核心业务逻辑
    		int addResult = target.add(i, j);
    		System.out.println("[日志] add 方法结束了,结果是:" + addResult);
    		return addResult;
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    静态代理确实实现了解耦,但是由于代码都写死了,完全不具备任何的灵活性。就拿日志功能来说,将来其他地方也需要附加日志,那还得再声明更多个静态代理类,那就产生了大量重复的代码,日志功能还是分散的,没有统一管理。
    提出进一步的需求:将日志功能集中到一个代理类中,将来有任何日志需求,都通过这一个代理类来实现。这就需要使用动态代理技术了。

    3、动态代理

    可以认为代理的是方法(接口/功能)
    代理的是对象做的事情
    体现:MyBatis基于Mapper(代理对象)的执行,AOP面向切面的底层就是动态代理

    动态代理流程图:
    在这里插入图片描述
    在这里插入图片描述
    生产代理对象的工厂类:

    package com.cy.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.util.Arrays;
    
    /**
     * Date:2022/7/4
     * Author:ybc
     * Description:
     */
    public class ProxyFactory {
    
        private Object target;
    
        public ProxyFactory(Object target) {
            this.target = target;
        }
    
        public Object getProxy(){
            /**
             * ClassLoader loader:指定加载动态生成的代理类的类加载器
             * Class[] interfaces:获取目标对象实现的所有接口的class对象的数组
             * InvocationHandler h:设置代理类中的抽象方法如何重写
             */
            ClassLoader classLoader = this.getClass().getClassLoader();
            Class<?>[] interfaces = target.getClass().getInterfaces();
            InvocationHandler h = new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = null;
                    try {
                        System.out.println("日志,方法:"+method.getName()+",参数:"+ Arrays.toString(args));
                        //proxy表示代理对象,method表示要执行的方法,args表示要执行的方法到的参数列表
                        result = method.invoke(target, args);
                        System.out.println("日志,方法:"+method.getName()+",结果:"+ result);
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println("日志,方法:"+method.getName()+",异常:"+ e);
                    } finally {
                        System.out.println("日志,方法:"+method.getName()+",方法执行完毕");
                    }
                    return result;
                }
            };
            return Proxy.newProxyInstance(classLoader, interfaces, h);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50

    测试方法:

    @Test
    public void testDynamicProxy(){
    	ProxyFactory factory = new ProxyFactory(new CalculatorLogImpl());
    	Calculator proxy = (Calculator) factory.getProxy();
    	proxy.div(1,0);
    	//proxy.div(1,1);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    (四)、AOP概念及相关术语

    1、概述

    AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面
    向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现在不修改源代码的情况下给程序动态统一添加额外功能的一种技术。
    面向对象OOP: 我们需要自己调用每一个小目标
    面向切面AOP: 我们只需要调用一个最终方法(中间隐藏着代理及每个小目标)

    2、相关术语

    ①横切关注点

    从每个方法中抽取出来的同一类非核心业务。在同一个项目中,我们可以使用多个横切关注点对相关方法进行多个不同方面的增强。
    这个概念不是语法层面天然存在的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横切关注点。

    ②通知

    每一个横切关注点上要做的事情都需要写一个方法来实现,这样的方法就叫通知方法。

    • 前置通知:在被代理的目标方法前执行
    • 返回通知:在被代理的目标方法成功结束后执行(寿终正寝)
    • 异常通知:在被代理的目标方法异常结束后执行(死于非命)
    • 后置通知:在被代理的目标方法最终结束后执行(盖棺定论)
    • 环绕通知:使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置
    ③切面

    封装通知方法的类。(切面是类,通知是类中的方法)

    ④目标

    被代理的目标对象。

    ⑤代理

    向目标对象应用通知之后创建的代理对象。

    ⑥连接点

    这也是一个纯逻辑概念,不是语法定义的。
    把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。
    在这里插入图片描述

    ⑦切入点

    定位连接点的方式。
    每个类的方法中都包含多个连接点,所以连接点是类中客观存在的事物(从逻辑上来说)。
    如果把连接点看作数据库中的记录,那么切入点就是查询记录的 SQL 语句。
    Spring 的 AOP 技术可以通过切入点定位到特定的连接点。
    切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

    3、作用

    简化代码:把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。
    代码增强:把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。

    4、切面的优先级

    相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。

    • 优先级高的切面:外面
    • 优先级低的切面:里面

    使用@Order注解可以控制切面的优先级:Order的值越大优先级越小,最大值为Integer的最大值

    • @Order(较小的数):优先级高
    • @Order(较大的数):优先级低

    如:

    package com.cy.annotation;
    
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    // @Aspect表示这个类是一个切面类
    @Aspect
    // @Component注解保证这个切面类能够放入IOC容器
    @Component
    @Order(1)//Order的值越大优先级越小,最大值为Integer的最大值
    public class VaildateAspect {
        @Before("execution(public int com.cy.annotation.CalculatorPureImpl.*(..))")
        public void beforeMethod(){
            System.out.println("VaildateAspect--->前置通知");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    (五)、基于注解的AOP

    1、技术说明

    在这里插入图片描述
    动态代理(InvocationHandler): JDK原生的实现方式,需要被代理的目标类必须实现接口。因
    为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
    cglib: 通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
    AspectJ: 本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最
    终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。

    2、案例

    ①添加依赖

    在IOC所需依赖基础上再加入下面依赖即可:

    
    <dependency>
    	<groupId>org.springframeworkgroupId>
    	<artifactId>spring-aspectsartifactId>
    	<version>5.3.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    如:

    
    <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.0modelVersion>
    
        <groupId>com.cygroupId>
        <artifactId>spring-aopartifactId>
        <version>1.0-SNAPSHOTversion>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
        <packaging>jarpackaging>
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.20version>
            dependency>
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-aspectsartifactId>
                <version>5.3.1version>
            dependency>
        dependencies>
    
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    ②准备被代理的目标资源

    接口:

    public interface Calculator {
    	int add(int i, int j);
    	int sub(int i, int j);
    	int mul(int i, int j);
    	int div(int i, int j);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    实现类:

    package com.cy.annotation;
    
    import org.springframework.stereotype.Component;
    
    @Component
    public class CalculatorPureImpl implements Calculator {
        @Override
        public int add(int i, int j) {
            int result = i + j;
            System.out.println("方法内部 result = " + result);
            return result;
        }
    
        @Override
        public int sub(int i, int j) {
            int result = i - j;
            System.out.println("方法内部 result = " + result);
            return result;
        }
    
        @Override
        public int mul(int i, int j) {
            int result = i * j;
            System.out.println("方法内部 result = " + result);
            return result;
        }
    
        @Override
        public int div(int i, int j) {
            int result = i / j;
            System.out.println("方法内部 result = " + result);
            return result;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    ③创建切面类并配置

    创建切面类:

    package com.cy.annotation;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    
    // @Aspect表示这个类是一个切面类
    @Aspect
    // @Component注解保证这个切面类能够放入IOC容器
    @Component
    public class LoggerAspect {
        /**
         * 在切面中,需要通过指定的注解将方法标识为通知方法
         *
         * @param joinPoint
         * @Before:前置通知的注解,在目标对象方法执行前执行
         */
        @Before("execution(public int com.cy.annotation.CalculatorPureImpl.*(..))")
        public void beforeMethod(JoinPoint joinPoint) {
            //获取连接点的签名信息
            String methodName = joinPoint.getSignature().getName();
            //获取目标方法到的实参信息
            String args = Arrays.toString(joinPoint.getArgs());
            System.out.println("Logger-->前置通知,方法名:" + methodName + ",参数:" + args);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在Spring的配置文件中配置:

    
    <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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
            
            <context:component-scan base-package="com.cy.annotation"/>
    
            
            <aop:aspectj-autoproxy/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3、各种通知及各种通知的执行顺序

    1、各种通知

    前置通知:使用@Before注解标识,在被代理的目标方法前执行
    返回通知:使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行(寿终正寝)
    异常通知:使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行(死于非命)
    后置通知:使用@After注解标识,在被代理的目标方法最终结束后执行(盖棺定论)
    环绕通知:使用@Around注解标识,使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置

    2、各种通知的执行顺序

    各种通知的执行顺序:
    Spring版本5.3.x以前:
    前置通知
    目标操作
    后置通知
    返回通知或异常通知
    Spring版本5.3.x以后:
    前置通知
    目标操作
    返回通知或异常通知
    后置通知

    4、切入点表达式语法

    ①作用

    在这里插入图片描述

    ②语法细节
    • 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限
    • 在包名的部分,一个“”号只能代表包的层次结构中的一层,表示这一层是任意的。
      例如:
      .Hello匹配com.Hello,不匹配com.atguigu.Hello
    • 在包名的部分,使用“*…”表示包名任意、包的层次深度任意
    • 在类名的部分,类名部分整体用*号代替,表示类名任意
    • 在类名的部分,可以使用*号代替类名的一部分
      例如:*Service匹配所有名称以Service结尾的类或接口
    • 在方法名部分,可以使用*号表示方法名任意
    • 在方法名部分,可以使用*号代替方法名的一部分
      例如:*Operation匹配所有方法名以Operation结尾的方法
    • 在方法参数列表部分,使用(…)表示参数列表任意
    • 在方法参数列表部分,使用(int,…)表示参数列表以一个int类型的参数开头
    • 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的
      切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
    • 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符
      例如:execution(public int …Service.(…, int)) 正确
      例如:execution(
      int …Service.*(…, int)) 错误
      在这里插入图片描述
      例如:
    package com.cy.annotation;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    
    // @Aspect表示这个类是一个切面类
    @Aspect
    // @Component注解保证这个切面类能够放入IOC容器
    @Component
    public class LoggerAspect {
        /**
         * 在切面中,需要通过指定的注解将方法标识为通知方法
         *
         * @param joinPoint
         * @Before:前置通知的注解,在目标对象方法执行前执行
         * 切入点表达式:设置在标识通知注解的value属性中
         * 如:@Before("execution(public int com.cy.annotation.CalculatorPureImpl.*(..))")或
         * @Before("execution(* com.cy.annotation.CalculatorPureImpl.*(..))")
         * 第一个*表示任意的访问修饰符和返回值类型
         * 第二个*表示类中任意的方法
         * ..表示任意的参数列表
         * 在类的地方也可以使用*,表示包下所有的类
         */
        @Before("execution(public int com.cy.annotation.CalculatorPureImpl.*(..))")
        public void beforeMethod() {
            System.out.println("Logger-->前置通知,");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    5、重用切入点表达式

    1、概念

    获取连接点的信息
    在通知方法的参数位置,设置类型的参数,就可以获取连接点对应方法的信息
    如:
    //获取连接点对应方法的签名信息
    String methodName = joinPoint.getSignature().getName
    //获取连接点对应目标方法到的实参信息
    String args = Arrays.toString(joinPoint.getArgs());

    2、用法一:局部的声明式表达式
    package com.cy.annotation;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    
    // @Aspect表示这个类是一个切面类
    @Aspect
    // @Component注解保证这个切面类能够放入IOC容器
    @Component
    public class LoggerAspect {
        /**
         * 3、获取连接点的信息
         * 在通知方法的参数位置,设置类型的参数,就可以获取连接点对应方法的信息
         * 如:
         * //获取连接点对应方法的签名信息
         * String methodName = joinPoint.getSignature().getName();
         * //获取连接点对应目标方法到的实参信息
         * String args = Arrays.toString(joinPoint.getArgs());
         */
        @Before("execution(public int com.cy.annotation.CalculatorPureImpl.*(..))")
        public void beforeMethod(JoinPoint joinPoint) {
            //获取连接点对应方法的签名信息
            String methodName = joinPoint.getSignature().getName();
            //获取目标方法到的实参信息
            String args = Arrays.toString(joinPoint.getArgs());
            System.out.println("Logger-->前置通知,方法名:" + methodName + ",参数:" + args);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    3、用法二:声明公共的切入点表达式
    ①在同一个切面中使用
    //1、声明
    @Pointcut("execution(* com.cy.annotation.*.*(..))")
    public void pointCut(){}
    //2、在同一个切面中使用
    @Before("pointCut()")
    public void beforeMethod(JoinPoint joinPoint){
    	String methodName = joinPoint.getSignature().getName();
    	String args = Arrays.toString(joinPoint.getArgs());
    	System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    ②在不同切面中使用
    @Before("com.cy.CommonPointCut.pointCut()")
    public void beforeMethod(JoinPoint joinPoint){
    	String methodName = joinPoint.getSignature().getName();
    	String args = Arrays.toString(joinPoint.getArgs());
    	System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    4、获取通知的相关信息
    ①获取连接点信息

    获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参

    @Before("execution(public int com.cy.annotation.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint){
    	//获取连接点的签名信息
    	String methodName = joinPoint.getSignature().getName();
    	//获取目标方法到的实参信息
    	String args = Arrays.toString(joinPoint.getArgs());
    	System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    ②获取目标方法的返回值

    在返回通知中若想要获取目标对象的返回值,只需要通过@AfterReturning中的属性returning,就可以将通知方法的某个参数 指定 为接收目标对象方法的返回值的参数

    @AfterReturning(value = "execution(* com.cy.annotation.CalculatorImpl.*(..))", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result){
    	String methodName = joinPoint.getSignature().getName();
    	System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    ③获取目标方法的异常

    在异常通知中若想要获取目标对象的异常,只需要通过@AfterThrowing中的属性throwing,就可以将通知方法的某个参数 指定 为接收目标对象方法出现的异常的参数

    @AfterThrowing(value = "execution(* com.cy.annotation.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
    	String methodName = joinPoint.getSignature().getName();
    	System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    5、环绕通知
    	/*环绕通知:
    		环绕通知的返回值一定要和目标对象的返回值一致
         * */
        @Around("execution(* com.cy.annotation.CalculatorPureImpl.*(..))")
        public Object aroundMethod(ProceedingJoinPoint joinPoint) {
            //获取连接点对应方法的签名信息
            String methodName = joinPoint.getSignature().getName();
            //获取目标方法到的实参信息
            String args = Arrays.toString(joinPoint.getArgs());
            Object result = null;
            try {
                System.out.println("环绕通知-->目标对象方法执行之前");
                //表示目标方法的执行,目标方法的返回值一定要返回给外界调用者
                result = joinPoint.proceed();
                System.out.println("环绕通知-->目标对象方法返回值之后");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                System.out.println("环绕通知-->目标对象方法出现异常时");
            } finally {
                System.out.println("环绕通知-->目标对象方法执行完毕");
            }
            return result;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    (六)、基于XML的AOP

    1、告知Spring帮我们进行对象/切面的管理

    <bean id=”获取对象时的name” class=”对象/切面所在的类”/>
    
    • 1

    2、做一个配置说明,说明那个时切面对象,切入点,通知/建议的配置,给切面对象做一个说明

     	 
        <aop:config>
             
            <aop:aspect id="mycut" ref="切面类的beanid,如果是注解扫描的方式配置的bean,则id为类的驼峰命名">
                
                <aop:pointcut id="mycut" expression="execution(* 包名.类名.方法名/>
                     
    	        "切面类中的方法名" pointcut-ref="切入点表达式的id"/>
    			<aop:after> 
    			<aop:after-returning>
    			<aop:agter-throwing> <aop:around>
            aop:aspect>
        aop:config>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    配置之后,直接访问目标即可
    如:
    切面类:

    package com.cy.xml;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.ProceedingJoinPoint;
    import org.aspectj.lang.annotation.*;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    
    // @Component注解保证这个切面类能够放入IOC容器
    @Component
    public class LoggerAspect {
    
        public void beforeMethod(JoinPoint joinPoint) {
            //获取连接点对应方法的签名信息
            String methodName = joinPoint.getSignature().getName();
            //获取目标方法到的实参信息
            String args = Arrays.toString(joinPoint.getArgs());
            System.out.println("Logger-->前置通知,方法名:" + methodName + ",参数:" + args);
        }
    
        public void afterMethod(JoinPoint joinPoint){
            String methodName = joinPoint.getSignature().getName();
            System.out.println("Logger-->后置通知,方法名:"+methodName);
        }
        /*
         * 在返回通知中若想要获取目标对象的返回值,只需要通过@AfterReturning中的属性returning,就可以将通知方法的某个参数 指定 为接收目标对象方法的返回值的参数
         * */
        public void afterReturningMethod(JoinPoint joinPoint, Object result) {
            String methodName = joinPoint.getSignature().getName();
            System.out.println("Logger-->返回通知,方法名:" + methodName + ",结果:" + result);
        }
    
        /*
        在异常通知中若想要获取目标对象的异常,只需要通过@AfterThrowing中的属性throwing,就可以将通知方法的某个参数 指定 为接收目标对象方法出现的异常的参数
        */
    
        public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex) {
            String methodName = joinPoint.getSignature().getName();
            System.out.println("Logger-->异常通知,方法名:" + methodName + ",异常:" + ex);
        }
    
        /*环绕通知:
         * */
    
        public Object aroundMethod(ProceedingJoinPoint joinPoint) {
            //获取连接点对应方法的签名信息
            String methodName = joinPoint.getSignature().getName();
            //获取目标方法到的实参信息
            String args = Arrays.toString(joinPoint.getArgs());
            Object result = null;
            try {
                System.out.println("环绕通知-->目标对象方法执行之前");
                //表示目标方法的执行,目标方法的返回值一定要返回给外界调用者
                result = joinPoint.proceed();
                System.out.println("环绕通知-->目标对象方法返回值之后");
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                System.out.println("环绕通知-->目标对象方法出现异常时");
            } finally {
                System.out.println("环绕通知-->目标对象方法执行完毕");
            }
            return result;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    配置文件:

    
    <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/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    
       
        <context:component-scan base-package="com.cy.xml"/>
    
        
        <aop:config>
            
            <aop:aspect ref="loggerAspect">
                
                <aop:pointcut id="pointCut" expression="execution(*com.cy.xml.CalculatorImpl.*(..))"/>
                
                <aop:before method="beforeMethod" pointcut-ref="pointCut"/>
                <aop:after method="afterMethod" pointcut-ref="pointCut"/>
                <aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointCut"/>
                <aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointCut"/>
                <aop:around method="aroundMethod" pointcut-ref="pointCut"/>
            aop:aspect>
            
            <aop:aspect ref="vaildateAspect" order="1">
                <aop:before method="beforeMethod" pointcut-ref="pointCut"/>
            aop:aspect>
        aop:config>
       
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    (七)、Spring的AOP总结

    例:我要从兰州出发到重庆吃火锅
    1.起始对象 兰州(没有真实存在main 项目开始)
    2.目标对象(Target Object) 重庆
    3.代理对象(AOP Proxy ) 代驾(Spring帮我们创建的 责任链模式)
    4.切面对象(Aspect) 好几个城市(沈阳 天津 济南 南京)
    5.切入点(Pointcut) 切入点 目标对象中的方法(吃火锅)
    6.连接点(Join point) 连接点 切面对象中的方法(加油 收费。。)
    7.建议/通知(Advice) 建议/通知 连接点中执行的过程(连接点方法中执行的过程)

    (八)、声明式事务

    1、JdbcTemplate

    1、简介

    Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作

    2、准备工作
    ①加入依赖
    
    <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.0modelVersion>
    
        <groupId>com.cygroupId>
        <artifactId>spring-transactionartifactId>
        <version>1.0-SNAPSHOTversion>
        <packaging>jarpackaging>
    
        <properties>
            <maven.compiler.source>8maven.compiler.source>
            <maven.compiler.target>8maven.compiler.target>
        properties>
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-contextartifactId>
                <version>5.3.1version>
            dependency>
            
            
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-ormartifactId>
                <version>5.3.1version>
            dependency>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-testartifactId>
                <version>5.3.1version>
            dependency>
            
            <dependency>
                <groupId>junitgroupId>
                <artifactId>junitartifactId>
                <version>4.12version>
                <scope>testscope>
            dependency>
            
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <version>8.0.16version>
            dependency>
            
            <dependency>
                <groupId>com.alibabagroupId>
                <artifactId>druidartifactId>
                <version>1.0.31version>
            dependency>
        dependencies>
    project>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    ②创建jdbc.properties
    jdbc.user=root
    jdbc.password=atguigu
    jdbc.url=jdbc:mysql://localhost:3306/ssm
    jdbc.driver=com.mysql.cj.jdbc.Driver
    
    • 1
    • 2
    • 3
    • 4
    ③配置Spring的配置文件
    
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/c"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
            
        <context:property-placeholder location="classpath:jdbc.properties" />
        
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="${jdbc.url}"/>
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        bean>
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            
            <property name="dataSource" ref="druidDataSource"/>
        bean>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    ④、测试
    package com.cy.text;
    
    import com.cy.pojo.User;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    
    import java.util.List;
    
    //指定当前测试类在Spring的测试环境中执行,此时就可以通过注入的方式直接获取IOC容器的bean
    @RunWith(SpringJUnit4ClassRunner.class)
    //设置Spring测试环境的配置文件
    @ContextConfiguration("classpath:spring-jdbc.xml")
    public class JDBCTemplateTest {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        @Test
        //测试增删改功能
        public void testUpdate(){
            String sql = "insert into t_user values(null,?,?,?)";
            int result = jdbcTemplate.update(sql, "张三", 23, "男");
            System.out.println(result);
        }
    
        @Test
        //查询一条数据为一个实体类对象
        public void testSelectEmpById(){
            String sql = "select * from t_user where id = ?";
            User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), 1);
            System.out.println(user);
        }
        @Test
        //查询多条数据为一个list集合
        public void testSelectList(){
            String sql = "select * from t_user";
            List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
            list.forEach(emp -> System.out.println(emp));
        }
    
        @Test
        //查询单行单列的值
        public void selectCount(){
            String sql = "select count(id) from t_user";
            Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
            System.out.println(count);
        }
    }
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    2、声明式事务概念

    1、编程式事务

    事务功能的相关操作全部通过自己编写代码来实现:

    	Connection conn = ...;
    	try {
    		// 开启事务:关闭事务的自动提交
    		conn.setAutoCommit(false);
    		// 核心操作
    		// 提交事务
    		conn.commit();
    	}catch(Exception e){
    		// 回滚事务
    		conn.rollBack();
    	}finally{
    		// 释放数据库连接
    		conn.close();
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    编程式的实现方式存在缺陷:

    • 细节没有被屏蔽:具体操作过程中,所有细节都需要程序员自己来完成,比较繁琐。
    • 代码复用性不高:如果没有有效抽取出来,每次实现功能都需要自己编写代码,代码就没有得到复用。
    2、声明式事务

    既然事务控制的代码有规律可循,代码的结构基本是确定的,所以框架就可以将固定模式的代码抽取出来,进行相关的封装。
    封装起来后,我们只需要在配置文件中进行简单的配置即可完成操作。
    好处1: 提高开发效率
    好处2: 消除了冗余的代码
    好处3: 框架会综合考虑相关领域中在实际开发环境下有可能遇到的各种问题,进行了健壮性、性能等各个方面的优化
    所以,我们可以总结下面两个概念:
    编程式: 自己写代码实现功能
    声明式: 通过配置让框架实现功能

    3、基于注解的声明式事务

    ①模拟场景

    用户购买图书,先查询图书的价格,再更新图书的库存和用户的余额
    假设用户id为1的用户,购买id为1的图书
    用户余额为50,而图书价格为80
    购买图书之后,用户的余额为-30,数据库中余额字段设置了无符号,因此无法将-30插入到余额字段
    此时执行sql语句会抛出SQLException

    ②观察结果

    因为没有添加事务,图书的库存更新了,但是用户的余额没有更新
    显然这样的结果是错误的,购买图书是一个完整的功能,更新库存和更新余额要么都成功要么都失败

    ③解决方案:加入事务
    1、声明式事务的配置(步骤):

    1、在spring配置文件中配置事务管理器
    2、开启事务的注解驱动
    3、通过注解@Transactional所标识的方法或标识的类中所有的方法,都会被事务管理器管理事务

    步骤1和2:添加事务配置并开启事务的注解驱动

    在Spring的配置文件中添加配置:

     
    <bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    	<property name="dataSource" ref="dataSource"/>
    bean>
    
    
    <tx:annotation-driven transaction-manager="transactionManager" />
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    注意:导入的名称空间需要 tx 结尾的那个。
    xmlns:tx=“http://www.springframework.org/schema/tx”
    如:

    
    <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:tx="http://www.springframework.org/schema/tx"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <context:component-scan base-package="com.cy"/>
    
        
        <context:property-placeholder location="classpath:jdbc.properties" />
        
        <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
            <property name="url" value="${jdbc.url}"/>
            <property name="driverClassName" value="${jdbc.driver}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
        bean>
        
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            
            <property name="dataSource" ref="druidDataSource"/>
        bean>
    
        
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="druidDataSource"/>
        bean>
        
        <tx:annotation-driven transaction-manager="transactionManager"/>
    beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    步骤3:添加事务注解

    因为service层表示业务逻辑层,一个方法表示一个完成的功能,因此处理事务一般在service层处理
    在BookServiceImpl的buybook()添加注解@Transactional
    如:

    package com.cy.service.Impl;
    
    import com.cy.dao.BookDao;
    import com.cy.service.BookService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    @Service
    public class BookServiceImpl implements BookService {
        @Autowired
        private BookDao bookDao;
        @Transactional
        @Override
        public void buyBook(Integer userId, Integer bookId) {
            //查询图书的价格
            Integer price = bookDao.getPriceByBookId(bookId);
            //更新图书的库存
            bookDao.updateStock(bookId);
            //更新用户的余额
            bookDao.updateBalance(userId, price);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    2、加入事务后观察结果

    由于使用了Spring的声明式事务,更新库存和更新余额都没有执行

    ④@Transactional注解标识的位置

    @Transactional标识在方法上,只会影响该方法
    @Transactional标识的类上,会影响类中所有的方法

    4、事务属性:

    1、只读
    ①介绍

    对一个查询操作来说,如果我们把它设置成只读,就能够明确告诉数据库,这个操作不涉及写操作。这样数据库就能够针对查询操作来进行优化。
    注意: 当事务中所有的操作都是查询操作时,才可以用只读属性

    ②使用方式
    @Transactional(readOnly = true)
    public void buyBook(Integer bookId, Integer userId) {
    	//查询图书的价格
    	Integer price = bookDao.getPriceByBookId(bookId);
    	//更新图书的库存
    	bookDao.updateStock(bookId);
    	//更新用户的余额
    	bookDao.updateBalance(userId, price);
    	//System.out.println(1/0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    ③注意

    对增删改操作设置只读会抛出下面异常:
    Caused by: java.sql.SQLException: Connection is read-only. Queries leading to data modification
    are not allowed

    2、超时
    ①介绍

    事务在执行过程中,有可能因为遇到某些问题,导致程序卡住,从而长时间占用数据库资源。而长时间占用资源,大概率是因为程序运行出现了问题(可能是Java程序或MySQL数据库或网络连接等等)。此时这个很可能出问题的程序应该被回滚,撤销它已做的操作,事务结束,把资源让出来,让其他正常程序可以执行。
    概括来说就是一句话:超时回滚,释放资源。

    ②使用方式
    @Transactional(timeout = 3)//3表示超时时间为3秒
    public void buyBook(Integer bookId, Integer userId) {
    	try {
    		TimeUnit.SECONDS.sleep(5);//让程序休眠5
    	} catch (InterruptedException e) {
    		e.printStackTrace();
    	}
    		//查询图书的价格
    		Integer price = bookDao.getPriceByBookId(bookId);
    		//更新图书的库存
    		bookDao.updateStock(bookId);
    		//更新用户的余额
    		bookDao.updateBalance(userId, price);
    		//System.out.println(1/0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    ③观察结果

    执行过程中抛出异常:
    org.springframework.transaction.TransactionTimedOutException: Transaction timed out:
    deadline was Fri Jun 04 16:25:39 CST 2022

    3、回滚策略
    ①介绍

    声明式事务默认只针对运行时异常回滚,编译时异常不回滚。
    可以通过@Transactional中相关属性设置回滚策略

    • rollbackFor属性:需要设置一个Class类型的对象(出现哪个异常需要回滚时用)
    • rollbackForClassName属性:需要设置一个字符串类型的全类名(出现哪个异常需要回滚时用)
    • noRollbackFor属性:需要设置一个Class类型的对象(出现哪个异常不需要回滚时用)
    • norollbackForClassName属性:需要设置一个字符串类型的全类名(出现哪个异常不需要回滚时用)
    ②使用方式
    @Transactional(noRollbackFor = ArithmeticException.class)
    //@Transactional(noRollbackForClassName = "java.lang.ArithmeticException")
    public void buyBook(Integer bookId, Integer userId) {
    	//查询图书的价格
    	Integer price = bookDao.getPriceByBookId(bookId);
    	//更新图书的库存
    	bookDao.updateStock(bookId);
    	//更新用户的余额
    	bookDao.updateBalance(userId, price);
    	System.out.println(1/0);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    ③观察结果

    虽然购买图书功能中出现了数学运算异常(ArithmeticException),但是我们设置的回滚策略是,当
    出现ArithmeticException不发生回滚,因此购买图书的操作正常执行

    4、事务隔离级别
    ①介绍

    数据库系统必须具有隔离并发运行各个事务的能力,使它们不会相互影响,避免各种并发问题。一个事务与其他事务隔离的程度称为隔离级别。SQL标准中规定了多种事务隔离级别,不同隔离级别对应不同的干扰程度,隔离级别越高,数据一致性就越好,但并发性越弱。
    隔离级别一共有四种:

    • 读未提交:READ UNCOMMITTED
      允许Transaction01读取Transaction02未提交的信息。可能出现脏读(读出来的数据没有任何意义)
    • 读已提交:READ COMMITTED、
      要求Transaction01只能读取Transaction02已提交的信息。可能出现读取的数据不一致(不可重复读)
    • 可重复读:REPEATABLE READ
      确保Transaction01可以多次从一个字段中读取到相同的值,即Transaction01执行期间禁止其它事务对这个字段进行更新。可能出现的幻读
    • 串行化:SERIALIZABLE
      确保Transaction01可以多次从一个表中读取到相同的行,在Transaction01执行期间,禁止其它
      事务对这个表进行添加、更新、删除操作。可以避免任何并发问题,但性能十分低下。
      各个隔离级别解决并发问题的能力见下表:
      在这里插入图片描述
      各种数据库产品对事务隔离级别的支持程度:
      在这里插入图片描述
    ②使用方式

    @Transactional(isolation = Isolation.DEFAULT)//使用数据库默认的隔离级别
    @Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
    @Transactional(isolation = Isolation.READ_COMMITTED)//读已提交
    @Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读
    @Transactional(isolation = Isolation.SERIALIZABLE)//串行化

    5、事务传播行为
    ①介绍

    当事务方法被另一个事务方法调用时,必须指定事务应该如何传播。例如:方法可能继续在现有事务中运行,也可能开启一个新事务,并在自己的事务中运行。

    ②测试

    创建接口CheckoutService:

    public interface CheckoutService {
    	void checkout(Integer[] bookIds, Integer userId);
    }
    
    • 1
    • 2
    • 3

    创建实现类CheckoutServiceImpl:

    @Service
    public class CheckoutServiceImpl implements CheckoutService {
    	@Autowired
    	private BookService bookService;
    	@Override
    	@Transactional
    	//一次购买多本图书
    	public void checkout(Integer[] bookIds, Integer userId) {
    		for (Integer bookId : bookIds) {
    		bookService.buyBook(bookId, userId);
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在BookController中添加方法:

    	@Autowired
    	private CheckoutService checkoutService;
    	public void checkout(Integer[] bookIds, Integer userId){
    		checkoutService.checkout(bookIds, userId);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在数据库中将用户的余额修改为100元

    ③观察结果

    可以通过@Transactional中的propagation属性设置事务传播行为
    修改BookServiceImpl中buyBook()上,注解@Transactional的propagation属性

    @Transactional(propagation = Propagation.REQUIRED),默认情况,表示如果当前线程上有已经开
    启的事务可用,那么就在这个事务中运行。经过观察,购买图书的方法buyBook()在checkout()中被调
    用,checkout()上有事务注解,因此在此事务中执行。所购买的两本图书的价格为80和50,而用户的余额为100,因此在购买第二本图书时余额不足失败,导致整个checkout()回滚,即只要有一本书买不
    了,就都买不了

    @Transactional(propagation = Propagation.REQUIRES_NEW),表示不管当前线程上是否有已经开启的事务,都要开启新事务。同样的场景,每次购买图书都是在buyBook()的事务中执行,因此第一本图书购买成功,事务结束,第二本图书购买失败,只在第二次的buyBook()中回滚,购买第一本图书不受影响,即能买几本就买几本

    (九)、基于XML的声明式事务

    1、场景模拟

    参考基于注解的声明式事务

    2、修改Spring配置文件

    将Spring配置文件中去掉tx:annotation-driven 标签,并添加配置:

    <aop:config>
    
    <aop:advisor advice-ref="txAdvice" pointcut="execution(*com.cy.tx.xml.service.impl.*.*(..))">aop:advisor>
    aop:config>
    
    
    
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
    
    
    <tx:method name="get*" read-only="true"/>
    <tx:method name="query*" read-only="true"/>
    <tx:method name="find*" read-only="true"/>
    
    
    
    
    
    
    <tx:method name="save*" read-only="false" rollbackfor="java.lang.Exception" propagation="REQUIRES_NEW"/>
    <tx:method name="update*" read-only="false" rollbackfor="java.lang.Exception" propagation="REQUIRES_NEW"/>
    <tx:method name="delete*" read-only="false" rollbackfor="java.lang.Exception" propagation="REQUIRES_NEW"/>
    tx:attributes>
    tx:advice>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    注意: 基于xml实现的声明式事务,必须引入aspectJ的依赖

    <dependency>
    	<groupId>org.springframeworkgroupId>
    	<artifactId>spring-aspectsartifactId>
    	<version>5.3.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    (十)、Spring注解的总结

    xml中做的配置 对象管理 机制scope lazy-init 自动注入 autowire=“byName”
    1.用于替代原有的bean标签 对象创建
    @Component MVC分层架构更加清晰
    控制层@Controller
    业务层@Service
    持久层@Repository
    2.用于替代原有bean标签中的属性 对象机制的管理
    @Scope(“singleton prototype”)
    @Lazy(true false)
    @PostConstructor 当前对象创建时执行的方法 method-init
    3.用于对象创建后的自动注入 当前对象销毁时执行的方法 method-destroy
    @ProDestroy
    @Autowired bvName方式 bvTvpe方式
    @Qualifier 搭配着上面的注解做一个对象的微调整
    @Value 支持SpEL rucation
    @Resource 不是Spring家族的注解
    4.以上注解都是写在自己定义的类中
    有些时候类不是我们写的 JdbcTemplate DataSource
    还想要通过注解的方式去管控这些对象
    1.自己定义类
    类中定义方法,作用是为了创建那些需要管控的对象
    方法通常有返回值,就是那些类的对象
    方法上面添加@Bean
    需要在自己写的类上面添加注解---->核心xml文件一样 让spring知道 读取@Configuration
    3.改变了原有读取xml文件的过程 创建工厂的方式也要相应进行改变
    BeanFactory factory = new AnnotationConfigApplicationContext(xxx.class
    4.如果我们想要添加一些外部文件的信息
    可以采用@PropertySource引入外部文件中的内容
    内容可以利用SpEL来读取
    5.自定义的类中可能会有很多的方法 dlucation其实可以将自定义类拆分 好多个小配置
    类,通过@Import(xxx.class)引入小配置类

  • 相关阅读:
    20.1 OpenSSL 字符BASE64压缩算法
    CentOS7的#!bash #!/bin/bash #!/bin/env bash #!/usr/bin/bash #!/usr/bin/env bash
    AI Studio vLoong能源AI挑战赛——异常检测赛A榜第三名方案
    Centos8系统配置Redis实现开机自启
    1.1. Java简介与安装
    测试计划一般包括什么?
    转置后再排列整理
    全屋Wi-Fi:一个谁也解决不好的痛点?
    Mysql: 创建表 和 管理表
    Linux常用命令、tomcat常用命令
  • 原文地址:https://blog.csdn.net/qq_45429856/article/details/127922129