001 spring5框架:java类工程,IOC:三层架构 实体类表示表关系,AOP,JdbcTemplate,事务操作,Spring5新功能:日志,为空注解,函数式风格,juint,Webflux

1. Spring5 框架(Spring5 Framework)介绍

1.1 概念

1、Spring 是轻量级的开源的 JavaEE 框架

2、Spring 可以解决企业应用开发的复杂性

3、Spring 有两个核心部分:IOC 和Aop
(1)IOC:控制反转,把创建对象过程交给 Spring 进行管理
(2)Aop:面向切面,不修改源代码进行功能增强

1.2 Spring 特点

(1)方便解耦,简化开发
(2)Aop 编程支持
(3)方便程序测试
(4)方便和其他框架进行整合
(5)方便进行事务操作
(6)降低 API 开发难度

1.3 Spring5 入门案例

说明:此课程中,选取 Spring 版本 5.x

1.3.1 下载 Spring5

1.进入到官网:spring.io
在这里插入图片描述
在这里插入图片描述
2.查看最新稳定版本:使用 Spring 最新稳定版本 GA,目前是5.3.16
在这里插入图片描述
3.具体的下载地址为:https://repo.spring.io/release/org/springframework/spring/
在这里插入图片描述
4.解压后的目录结构
在这里插入图片描述

1.3.2 打开 idea 工具,创建普通 Java 工程

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

1.3.3 导入 Spring5 相关 jar 包

说明:入门案例只做基本功能,暂时只需要以下4个jar包,以及一个依赖的log包。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

1.3.4 创建普通类,在这个类创建普通方法

说明:创建此类的对象以前都是new的方式,现在通过spring的方式创建,可以通过注解也可以通过配置文件。
在这里插入图片描述

public class User { 
    public void add() { 
        System.out.println("add.	"); 
    } 
} 

1.3.5 创建 Spring 配置文件,在配置文件配置创建的对象

说明:以配置文件的方式为例创建对象。

(1)Spring 配置文件使用 xml 格式,在src目录下右键…
在这里插入图片描述
(2)通过bean标签创建对象
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1 配置User对象创建:别名,类全路径-->
    <bean id="user" class="com.atguigu.spring5.User"></bean>

</beans>

1.3.6 进行测试代码编写

package com.atguigu.testdemo;

import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {

    @Test
    public void testAdd() {
        //1 加载spring配置文件  类路径,如果配置文件是在src下可以直接写文件名,如果不是再加上路径
        //BeanFactory 可以换成ApplicationContext,区别:查看2.2
        BeanFactory context = new ClassPathXmlApplicationContext("bean1.xml");

        //2 获取配置创建的对象 (配置文件的别名,转化的类型)
        User user = context.getBean("user", User.class);

        System.out.println(user);
        user.add();
    }


}

在这里插入图片描述

2. IOC

2.1 背景、概念、原理

2.1.1 背景:三层架构+分层解耦

  • 问题1:所有的代码都写在Controller类中,这样代码的复用性和拓展性都比较差,项目也会变得难以维护。

  • 解决:三层架构:
    在这里插入图片描述

    • 代码拆分前后对比:
      在这里插入图片描述
  • 问题2:为什么要使用分层解耦

    • 内聚 解释:比如员工管理的Service类,只会编写与员工相关的逻辑处理,而与员工无关的逻辑处理不会放在这个类中。
    • 耦合 解释:Controller调用Service层时他需要使用Service层的对象,所以需要在Controller层new一个Service的实现类对象,如果此时需要切换一个Service层实现类,那么就要修改控制层创建实现类对象的代码,这就成为Controller层与Service层的代码耦合了。
    • 软件设计原则:模块内部的联系越紧密越好,模块与模块之间的耦合性越低越好。即:高内聚低耦合在这里插入图片描述
  • 解决:想要解耦就不能像之前那样直接在Controller层new Service层的实现类对象,可以把Service层创建的对象放到一个容器中,程序运行时如果Controller类需要用到Service层类的对象,只需要把容器中的Service对象注入到控制层即可。这样控制层一旦切换实现类,只需要把这个新的实现类对象创建好后放到容器中,控制层从容器中注入这个对象即可。好处:即使Service层的实现类发生变化了,Controller层的代码也不需要修改,这样就完成了解耦。

    • 存在2个问题:对象如何交给容器去管理,容器如何为程序提供所依赖的资源。
    • 解决:控制反转、依赖注入。
      在这里插入图片描述

2.1.2 什么是 IOC

(1)控制反转,把对象创建和对象之间的调用过程,交给 Spring 进行管理
(2)使用 IOC 目的:为了耦合度降低
(3)做入门案例就是 IOC 实现

2.1.3 IOC 底层原理

(1)底层原理涉及到的技术:xml 解析、工厂模式、反射
(2)画图讲解 IOC 底层原理

原始方式创建对象:
在这里插入图片描述
工厂模式创建对象:可以降低一部分耦合度,但不能降到最低。
在这里插入图片描述
IOC创建对象:可以把耦合性降到最低
在这里插入图片描述

2.2 IOC(BeanFactory 接口)

1、IOC 思想基于 IOC 容器完成,IOC 容器底层就是对象工厂

2、Spring 提供 IOC 容器实现两种方式:(两个接口)
(1) BeanFactory:IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用。
特点:加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象

(2) ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人员进行使用
特点: 加载配置文件时候就会把在配置文件对象进行创建

思考:那种接口方式更好???
ApplicationContext方式更好,因为不能单单的只考虑内存方面,啥时候用啥时候创建对象是可以节约一部分内存。但是这里用的是spring框架,spring框架一般需要结合web项目进行操作,比如需要使用tomact服务器启动时候这种耗时耗资源的操作,把这种操作都交给项目在启动的时候 用服务器解析xml文件创建对象,服务器处理当然速度更快。

3、ApplicationContext 接口有实现类

2个常用实现类的区别:ApplicationContext 和BeanFactory都有
FileSystem…的路径需要写:电脑的磁盘路径。
ClassPath…的路径需要写:类路径(src下的路径可以直接写)
在这里插入图片描述
在这里插入图片描述

2.3 IOC 操作 Bean 管理

2.3.1 概念:什么是 Bean 管理

Bean 管理指的是两个操作:
(1)Spring 创建对象- - -(普通方式是new)
(2)Spirng 注入属性- - -(普通方式是调用set方法)

2.3.2 Bean 管理操作有两种方式:

(1)基于 xml 配置文件方式实现 ,创建对象,注入属性。
(2)基于注解方式实现,创建对象,注入属性。

2.3.3 IOC 操作 普通Bean 管理(基于xml–不推荐)

2.3.3.1 xml 方式创建 对象

说明1:在 spring 配置文件中,使用 bean 标签,标签里面添加对应属性,就可以实现对象创建。
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1 配置User对象创建:别名(前类的对象名),类全路径-->
    <bean id="user" class="com.atguigu.spring5.User"></bean>

</beans>

说明2:在 bean 标签有很多属性,介绍常用的属性

id    属性:唯一标识
class 属性:类全路径(包类路径)

说明3:和之前一样,默认使用的是无参构造方法完成对象的创建

2.3.3.2 xml 方式注入 属性

说明:依赖注入(DI),就是注入属性
注意:属性注入要在创建对象的基础之上完成。

方式一:使用 set 方法进行注入。
测试步骤1):创建类,定义属性和对应的 set 方法

package com.atguigu.spring5;

/**
 * 演示使用set方法进行注入属性
 */
public class Book {
    //创建属性
    private String bname;
    private String bauthor;

    //创建属性对应的set方法
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }



    //此方法只是为了测试类里面的方法进行测试用的
    public void testDemo() {
        System.out.println(bname+"::"+bauthor);
    }
}



测试步骤2):在 spring 配置文件bean1.xml配置对象创建,配置属性注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    

    <!--1 配置User对象创建:别名,类全路径-->
    <bean id="book" class="com.atguigu.spring5.Book">
        <!--2 set方法注入属性-->
        <!--使用property完成属性注入
            name:类里面属性名称
            value:向属性注入的值
        -->
        <property name="bname" value="易筋经"></property>
        <property name="bauthor" value="达摩老祖"></property>
       
    </bean>

</beans>

测试步骤3):在TestSpring5测试类中进行测试

package com.atguigu.testdemo;

import com.atguigu.spring5.Book;
import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {


    @Test
    public void testBook1() {
        //1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");

        //2 获取配置创建的对象
        Book book = context.getBean("book", Book.class);

        System.out.println(book);
        book.testDemo();
    }


}

在这里插入图片描述

方式二:使用有参数构造进行注入。
测试步骤1):创建类,定义属性,创建属性对应有参数构造方法

package com.atguigu.spring5;

/**
 * 使用有参数构造注入
 */
public class Orders {
    //属性
    private String oname;
    private String address;
    //有参数构造
    public Orders(String oname,String address) {
        this.oname = oname;
        this.address = address;
    }
    //此方法只是为了测试类里面的方法进行测试用的
    public void ordersTest() {
        System.out.println(oname+"::"+address);
    }
}

测试步骤2):在 spring 配置文件bean1.xml配置对象创建,配置属性注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


    <!--3 有参数构造注入属性-->
    <!--注意:使用有参构造调用的是有参构造创建的对象,不再是无参构造创建对象了-->
    <bean id="orders" class="com.atguigu.spring5.Orders">
        <!--方式1:通过参数名 推荐,这种更加准确-->
        <constructor-arg name="oname" value="电脑"></constructor-arg>
        <constructor-arg name="address" value="China"></constructor-arg>
        <!--方式2:通过索引值,0代表有参构造方法的第一个参数-->
        <!--<constructor-arg index="0" value="China"></constructor-arg>-->
    </bean>

</beans>

测试步骤3):在TestSpring5测试类中进行测试

package com.atguigu.testdemo;

import com.atguigu.spring5.Book;
import com.atguigu.spring5.User;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5 {


   @Test
    public void testOrders() {
        //1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");

        //2 获取配置创建的对象
        Orders orders = context.getBean("orders", Orders.class);

        System.out.println(orders);
        orders.ordersTest();
    }


}

在这里插入图片描述

方式三:p 名称空间注入(了解)。

说明:使用 p 名称空间注入,可以简化基于 xml 配置方式使用set方法注入属性,底层调用的仍然是set方法。(方式一的简化)

测试步骤1)添加 p 名称空间在配置文件中

在这里插入图片描述

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

测试步骤2)进行属性注入,在 bean 标签里面进行操作
在这里插入图片描述

<!--2 set 方法注入属性--> 
<bean id="book" class="com.atguigu.spring5.Book" p:bname="九阳神功" p:bauthor="无名氏"></bean> 
2.3.3.3 xml 方式注入 字面量属性

字面量含义:在类里面的变量上直接赋值一个固定值叫做字面量。

普通方式设置字面量:
在这里插入图片描述

xml文件的标签形式设置字面量

案例1:xml方式的字面量是null 值

Book类:
在这里插入图片描述

package com.atguigu.spring5;

/**
 * 演示使用set方法进行注入属性
 */
public class Book {
    //创建属性
    private String bname="";
    private String bauthor;
    private String address;

    //创建属性对应的set方法
    public void setBname(String bname) {
        this.bname = bname;
    }
    public void setBauthor(String bauthor) {
        this.bauthor = bauthor;
    }
    public void setAddress(String address) {
        this.address = address;
    }

    //此方法只是为了测试类里面的测试方法进行测试用的
    public void testDemo() {
        System.out.println(bname+"::"+bauthor+"::"+address);
    }
}

bean1.xml:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--2 set方法注入属性-->
    <bean id="book" class="com.atguigu.spring5.Book">
        <!--使用property完成属性注入
            name:类里面属性名称
            value:向属性注入的值
        -->
        <property name="bname" value="易筋经"></property>
        <property name="bauthor" value="达摩老祖"></property>

        <!--null值-->
        <property name="address">
            <null/>
        </property>


    </bean>




</beans>

运行测试:
在这里插入图片描述

案例2:xml方式的字面量包含特殊符号

bean1.xml:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--2 set方法注入属性-->
    <bean id="book" class="com.atguigu.spring5.Book">
        <!--使用property完成属性注入
            name:类里面属性名称
            value:向属性注入的值
        -->
        <property name="bname" value="易筋经"></property>
        <property name="bauthor" value="达摩老祖"></property>

        <!--null值-->
        <!--<property name="address">
            <null/>
        </property>-->

        <!--属性值包含特殊符号
            方式一: 把<>进行转义 &lt; &gt;
            方式二: 把带特殊符号内容写到CDATA
        -->
        <property name="address">
            <value><![CDATA[<<南京>>]]></value>
        </property>


    </bean>




</beans>

运行测试:
在这里插入图片描述

2.3.3.4 xml 方式注入 外部 bean

解释:service层调用dao层就叫做引入外部bean.

测试步骤:
(1)创建两个类 service 类和 dao 类
(2)在 service 调用 dao 里面的方法
(3)在 spring 配置文件中进行配置

类UserService

package com.atguigu.service;

import com.atguigu.dao.UserDao;
import com.atguigu.dao.UserDaoImpl;

public class UserService {


    //需:1:原始方式,在UserService中调用UserDao里面的的方法
    public void add1() {
        System.out.println("service add1...............");
        //创建UserDao对象
        UserDao userDao = new UserDaoImpl();
        userDao.update1();

    }
    //需求2:xml方式,在UserService中调用UserDao里面的的方法
    //   步骤1:创建UserDao类型属性,生成set方法。(注意:写的的是想要注入的对象类型)
    //   步骤2:需要在xml文件中进行配置
    private UserDao userDao;
    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void add() {
        System.out.println("service add...............");
        userDao.update();
    }

}

接口UserDao

package com.atguigu.dao;

public interface UserDao {

    public void update1();
    public void update();
}

接口实现类UserDaoImpl :

package com.atguigu.dao;

public class UserDaoImpl implements UserDao {

    @Override
    public void update1() {

        System.out.println("dao update1...........");
    }

    @Override
    public void update() {
        System.out.println("dao update...........");
    }
}

bean2.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1 service和dao对象创建-->
    <bean id="userService" class="com.atguigu.service.UserService">
        <!--注入userDao对象
            name属性:类里面属性名称
            ref属性:创建userDao对象bean标签id值  
            注意内部bean:注入的是对象类型用ref属性表示,
            值为下面bean标签的id值userDaoImpl即想要注入对象的别名
        -->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <!--UserDao是个接口不能new对象,只能是找他的实现类创建对象-->
    <bean id="userDaoImpl" class="com.atguigu.dao.UserDaoImpl"></bean>
</beans>

测试类TestBean

package com.atguigu.testdemo;


import com.atguigu.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

    @Test
    public void testBean1() {
        //1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");

        //2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);

        userService.add();
    }


}

在这里插入图片描述

2.3.3.5 xml 方式注入 内部 bean (表关系)
  1. 一对多关系:部门和员工
    解释:一个部门有多个员工,一个员工属于一个部门,部门是一,员工是多
  2. 在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示
  3. 在 spring 配置文件中进行配置

Dept类:

package com.atguigu.bean;

//部门类
public class Dept {
    private String dname;
    public void setDname(String dname) {
        this.dname = dname;
    }

    @Override
    public String toString() {
        return "Dept{" +
                "dname='" + dname + '\'' +
                '}';
    }
}

Emp类:

package com.atguigu.bean;

//员工类
public class Emp {
    private String ename;
    private String gender;
    //员工属于某一个部门,使用对象形式表示
    private Dept dept;//在类上如何表示一对多的表关系

    public void setDept(Dept dept) {
        this.dept = dept;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }

    public void add() {
        System.out.println(ename+"::"+gender+"::"+dept);
    }
}

bean3.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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-->
    <bean id="emp" class="com.atguigu.bean.Emp">
        <!--设置两个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value=""></property>
        <!--设置对象类型属性,内部bean写法。当然也可以使用外部bean的写法。-->
        <property name="dept">
            <bean id="dept" class="com.atguigu.bean.Dept">
                <property name="dname" value="安保部"></property>
            </bean>
        </property>
    </bean>
</beans>

TestBean类:

package com.atguigu.testdemo;


import com.atguigu.bean.Emp;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

    @Test
    public void testBean2() {
        //1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");

        //2 获取配置创建的对象
        Emp emp = context.getBean("emp", Emp.class);

        emp.add();
    }


}

在这里插入图片描述

2.3.3.6 xml 方式注入 级联赋值

说明:可以理解为内部bean的另一种写法

方式一:

Dept和Emp类同上没有变化,略。

bea4.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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="emp" class="com.atguigu.bean.Emp">
        <!--设置两个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value=""></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
    </bean>
    <bean id="dept" class="com.atguigu.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>


</beans>

TestBean类

package com.atguigu.testdemo;


import com.atguigu.bean.Emp;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBean {

    @Test
    public void testBean2() {
        //1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean4.xml");

        //2 获取配置创建的对象
        Emp emp = context.getBean("emp", Emp.class);

        emp.add();
    }


}

在这里插入图片描述
(2)方式二

dept类、TestBean测试类同上不变。

修改Emp类:提供属性对应的get方法
在这里插入图片描述

package com.atguigu.bean;

//员工类
public class Emp {
    private String ename;
    private String gender;
    //员工属于某一个部门,使用对象形式表示
    private Dept dept;

    //生成dept的get方法
    public Dept getDept() {
        return dept;
    }

    public void setDept(Dept dept) {
        this.dept = dept;
    }
    public void setEname(String ename) {
        this.ename = ename;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }

    public void add() {
        System.out.println(ename+"::"+gender+"::"+dept);
    }
}

修改bean4.xml:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns: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="emp" class="com.atguigu.bean.Emp">
        <!--设置两个普通属性-->
        <property name="ename" value="lucy"></property>
        <property name="gender" value=""></property>
        <!--级联赋值-->
        <property name="dept" ref="dept"></property>
        <property name="dept.dname" value="技术部"></property>
    </bean>
    <bean id="dept" class="com.atguigu.bean.Dept">
    </bean>


</beans>

测试:
在这里插入图片描述

2.3.3.7 xml 方式注入 数组,集合属性(值是字符串)

1、注入数组类型属性
2、注入 List 集合类型属性
3、注入 Map 集合类型属性
4、注入 Set 集合类型属性
测试:
(1)创建类,定义数组、list、map、set 类型属性,生成对应 set 方法。

package com.atguigu.spring5.collectiontype;

import java.util.List;
import java.util.Map;
import java.util.Set;

public class Stu {
    //1 数组类型属性
    private String[] courses;
    //2 list集合类型属性
    private List<String> list;
    //3 map集合类型属性
    private Map<String,String> maps;
    //4 set集合类型属性
    private Set<String> sets;

    public void setSets(Set<String> sets) {
        this.sets = sets;
    }
    public void setCourses(String[] courses) {
        this.courses = courses;
    }
    public void setList(List<String> list) {
        this.list = list;
    }
    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }
}

(2)在 spring 配置文件进行配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1 集合类型属性注入-->
    <bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">
        <!--数组类型属性注入:使用list或者array-->
        <property name="courses">
            <array>
                <value>java课程</value>
                <value>数据库课程</value>
            </array>
        </property>
        <!--list类型属性注入-->
        <property name="list">
            <list>
                <value>张三</value>
                <value>小三</value>
            </list>
        </property>
        <!--map类型属性注入-->
        <property name="maps">
            <map>
                <entry key="JAVA" value="java"></entry>
                <entry key="PHP" value="php"></entry>
            </map>
        </property>
        <!--set类型属性注入-->
        <property name="sets">
            <set>
                <value>MySQL</value>
                <value>Redis</value>
            </set>
        </property>
       
    </bean>
    
</beans>

测试类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collectiontype.Stu;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testCollection1() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        Stu stu = context.getBean("stu", Stu.class);
        stu.test();
    }


}

在这里插入图片描述

2.3.3.8 xml 方式注入 数组,集合属性(值是对象)

bean1.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--1 集合类型属性注入-->
    <bean id="stu" class="com.atguigu.spring5.collectiontype.Stu">

        <!--注入list集合类型,值是对象-->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
    </bean>

    <!--创建多个course对象-->
    <bean id="course1" class="com.atguigu.spring5.collectiontype.Course">
        <property name="cname" value="Spring5框架"></property>
    </bean>
    <bean id="course2" class="com.atguigu.spring5.collectiontype.Course">
        <property name="cname" value="MyBatis框架"></property>
    </bean>
</beans>

Course类:

package com.atguigu.spring5.collectiontype;

//课程类
public class Course {
    private String cname; //课程名称
    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}

Stu类:

package com.atguigu.spring5.collectiontype;

import java.util.List;

public class Stu {


    //学生所学多门课程
    private List<Course> courseList;
    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }


    public void test() {

        System.out.println(courseList);
    }
}

TestSpring5Demo1类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collectiontype.Stu;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testCollection1() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        Stu stu = context.getBean("stu", Stu.class);
        stu.test();
    }


}

在这里插入图片描述

4.7、xml 注入集合属性----》把集合注入部分提取出来
说明:之前只能对当前bean有效,把它抽取出来可以用于设置不同的对象bean中xml 注入集合属性。

(1)在 spring 配置文件中引入名称空间 util
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

  
</beans>

(2)使用 util 标签完成 list 集合注入提取
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <!--1 提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>易筋经</value>
        <value>九阴真经</value>
        <value>九阳神功</value>
    </util:list>

    <!--2 提取list集合类型属性注入使用-->
    <bean id="book" class="com.atguigu.spring5.collectiontype.Book" >
        <property name="list" ref="bookList"></property>
    </bean>

</beans>

Book类:

package com.atguigu.spring5.collectiontype;

import java.util.List;

public class Book {
    private List<String> list;
    public void setList(List<String> list) {
        this.list = list;
    }

    public void test() {
        System.out.println(list);
    }

}

TestSpring5Demo1测试类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collectiontype.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {



    @Test
    public void testCollection2() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);

         book.test();

    }


}

在这里插入图片描述

2.3.4 IOC 操作 FactoryBean 管理(基于xml)

1、Spring 有两种类型 bean,一种普通 bean,另外一种工厂 bean(FactoryBean)
2、普通 bean:在配置文件中定义 bean 类型就是返回类型
3、工厂 bean在配置文件定义 bean 类型可以和返回类型不一样

步骤
第一步:创建类,让这个类作为工厂 bean,实现接口 FactoryBean
第二步:实现接口里面的方法,在实现的方法中定义返回的 bean 类型

bean3.xml:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="myBean" class="com.atguigu.spring5.factorybean.MyBean">
    </bean>
</beans>

Course类:

package com.atguigu.spring5.collectiontype;

//课程类
public class Course {
    private String cname; //课程名称
    public void setCname(String cname) {
        this.cname = cname;
    }

    @Override
    public String toString() {
        return "Course{" +
                "cname='" + cname + '\'' +
                '}';
    }
}

MyBean类:

package com.atguigu.spring5.factorybean;

import com.atguigu.spring5.collectiontype.Course;
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {

    //定义返回bean
    @Override
    public Course getObject() throws Exception {
        Course course = new Course();
        course.setCname("abc");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}

TestSpring5Demo1测试类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collectiontype.Course;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {



    @Test
    public void test3() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");
        //配置文件定义的类型可以和返回值类型不同
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }


}

在这里插入图片描述

2.3.5 IOC 管理 bean作用域(单例,多例)

说明1:在 Spring 里面,默认情况下,创建的bean 实例是单实例对象

在xml中创建对象
在这里插入图片描述
获取2个对象,并输出,发现地址值相同,说明是同一个对象。
在这里插入图片描述

说明2:如何设置单实例还是多实例

  1. 在 spring 配置文件 bean 标签里面有属性(scope)用于设置单实例还是多实例
  2. scope 属性值:
    第一个值 默认值,singleton,表示是单实例对象
    第二个值 prototype,表示是多实例对象
  3. singleton 和 prototype 区别
    第一 :singleton 单实例,prototype 多实例
    第二 :设置 scope 值是 singleton 时候,加载 spring 配置文件时候就会创建单实例象。设置 scope 值是 prototype 时候,不是在加载 spring 配置文件时候创建对象,在调用getBean 方法时候创建多实例对象

bean2.xml:
在xml中创建对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    <!--1 提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>易筋经</value>
        <value>九阴真经</value>
        <value>九阳神功</value>
    </util:list>

    <!--2 提取list集合类型属性注入使用-->
    <bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
    </bean>

</beans>

在这里插入图片描述
测试类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.collectiontype.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testCollection2() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book1 = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);
        // book.test();
        System.out.println(book1);
        System.out.println(book2);
    }





}

获取2个对象,并输出,发现地址值不同,说明不是同一个对象。
在这里插入图片描述

2.3.6 IOC 管理 Bean生命周期

  1. 生命周期
    (1)对象创建到对象销毁的过程

  2. bean 生命周期
    (1)通过构造器创建 bean 实例(无参数构造)
    (2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
    (3)调用 bean 的初始化的方法(需要进行配置初始化的方法)
    (4)bean 可以使用了(对象获取到了)
    (5)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

演示 bean 生命周期
bean4.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>


</beans>

Orders类:

package com.atguigu.spring5.bean;

public class Orders {

    //无参数构造
    public Orders() {
        System.out.println("第一步 执行无参数构造创建bean实例");
    }

    private String oname;
    public void setOname(String oname) {
        this.oname = oname;
        System.out.println("第二步 调用set方法设置属性值");
    }

    //创建执行的初始化的方法
    public void initMethod() {
        System.out.println("第三步 执行初始化的方法");
    }

    //创建执行的销毁的方法
    public void destroyMethod() {
        System.out.println("第五步 执行销毁的方法");
    }
}

TestSpring5Demo1测试类:

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.bean.Orders;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testBean3() {
//        ApplicationContext context =
//                new ClassPathXmlApplicationContext("bean4.xml");
        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext("bean4.xml");
        Orders orders = context.getBean("orders", Orders.class);
        System.out.println("第四步 获取创建bean实例对象");
        System.out.println(orders);

        //手动让bean实例销毁
        context.close();
    }





}

在这里插入图片描述
3、bean 的后置处理器,bean 完整的生命周期有七步
(1)通过构造器创建 bean 实例(无参数构造)
(2)为 bean 的属性设置值和对其他 bean 引用(调用 set 方法)
(3)把 bean 实例传递 bean 前置处理器的方法 postProcessBeforeInitialization
(4)调用 bean 的初始化的方法(需要进行配置初始化的方法)
(5)把 bean 实例传递 bean 后置处理器的方法 postProcessAfterInitialization
(6)bean 可以使用了(对象获取到了)
(7)当容器关闭时候,调用 bean 的销毁的方法(需要进行配置销毁的方法)

演示添加后置处理器效果

说明:创建类,实现接口 BeanPostProcessor,创建后置处理器。
MyBeanPost:

package com.atguigu.spring5.bean;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class MyBeanPost implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之前执行的方法");
        return bean;
    }
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("在初始化之后执行的方法");
        return bean;
    }
}

bean4.xml:
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean id="orders" class="com.atguigu.spring5.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="手机"></property>
    </bean>

    <!--配置后置处理器-->
    <bean id="myBeanPost" class="com.atguigu.spring5.bean.MyBeanPost"></bean>


</beans>

在这里插入图片描述

2.3.7 IOC 操作 Bean 管理(xml 自动装配)

说明:根据指定装配规则(属性名称或者属性类型),Spring 自动将匹配的属性值进行注入。好处是不用自己在手动指定了,简化了代码更加方便。

之前是在web.xml配置文件的标签中,手动指定属性的名称和属性值 eg:
在这里插入图片描述

演示自动装配过程:
(1)根据属性名称自动注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性常用两个值:
            byName根据属性名称注入 ,注入值bean的id值和类属性名称一样
            byType根据属性类型注入
    -->
    <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byName">
        <!-- 手动装配:<property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

</beans>

(2)根据属性类型自动注入

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <!--实现自动装配
        bean标签属性autowire,配置自动装配
        autowire属性常用两个值:
            byName根据属性名称注入 ,注入值bean的id值和类属性名称一样
            byType根据属性类型注入
    -->
    <bean id="emp" class="com.atguigu.spring5.autowire.Emp" autowire="byType">
        <!-- 手动装配:<property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="com.atguigu.spring5.autowire.Dept"></bean>

</beans>

Dept 类:

package com.atguigu.spring5.autowire;

public class Dept {
    @Override
    public String toString() {
        return "Dept{}";
    }
}

Emp类:

package com.atguigu.spring5.autowire;

public class Emp {
    private Dept dept;//在Emp类中注入对象类型属性dept,底层调用setDept方法
    public void setDept(Dept dept) {
        this.dept = dept;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "dept=" + dept +
                '}';
    }

    public void test() {
        System.out.println(dept);
    }
}

在这里插入图片描述

2.3.8 IOC 操作 Bean 管理(外部属性文件)

应用场景:一个类中的属性很多,赋值需要写很多标签,并且发生变化时需要改xml配置文件,这样写太过麻烦。

解决:可以把相关的值放到配置文件中,在引入到xml文件中进行读取。

方式一:直接配置数据库信息,配置德鲁伊连接池
(1)引入德鲁伊连接池依赖 jar 包

在这里插入图片描述
(2)在Spring的xml文件中添加配置

 <!--直接配置连接池-->
  <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>

方式二:引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties 格式文件,写数据库信息。
在这里插入图片描述

prop.driverClass=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/userDb
prop.userName=root
prop.password=root

(2)把外部 properties 属性文件引入到 spring 配置文件中

  • 引入 context 名称空间
    在这里插入图片描述

  • 在 spring 配置文件使用标签引入外部属性文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       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/util http://www.springframework.org/schema/util/spring-util.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--直接配置连接池-->
    <!--<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
        <property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
        <property name="username" value="root"></property>
        <property name="password" value="root"></property>
    </bean>-->

    <!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置连接池   这是通过Spring提供的EL表达式取值-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${prop.driverClass}"></property>
        <property name="url" value="${prop.url}"></property>
        <property name="username" value="${prop.userName}"></property>
        <property name="password" value="${prop.password}"></property>
    </bean>

</beans>

在这里插入图片描述

2.3.9 IOC 操作 Bean 管理(基于注解方式—推荐)

说明:注解方式创建对象和注入属性的详细种类方式,在Spring注解驱动开发教程、Spring6中讲解,这里只是简单地讲解其中的几种方式。

什么是注解:

  1. 注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
  2. 使用注解,注解作用在上面,方法上面,属性上面
  3. 使用注解目的:简化 xml 配置
2.3.9.1 注解方式 创建对象

说明:上面四个注解功能是一样的,都可以用来创建bean 实例。它们之间可以混用,只不过建议根据它的含义写在不同的层次结构中,目的是让开发人员更加清晰当前组件所扮演的角色

  1. @Component----->spring容器提供的普通注解
  2. @Controller----->一般用在controller层
  3. @Service----->一般用在service层
  4. @Repository----->一般用在dao层
  5. 注意:以上注解是用在类上为当前类创建对象
  6. 局限:只能用于自己写的类。

步骤一: 引入依赖
在这里插入图片描述
步骤二: 开启组件扫描
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描
       方式1 如果扫描多个包,多个包使用逗号隔开
       方式2 扫描包上层目录
    -->
    <!--<context:component-scan base-package="com.atguigu.spring5.dao,com.atguigu.spring5.service"></context:component-scan>-->
    <context:component-scan base-package="com.atguigu.spring5"></context:component-scan>

</beans>

步骤三:创建类,在类上面添加创建对象注解

package com.atguigu.spring5.service;

import org.springframework.stereotype.Service;
/**
 *正常写法:value的值为创建当前类的对象名,这个名字可以手动指定。
 *   @Component(value = "userService")  //相当于xml标签的 id值:<bean id="userService" class=".."/>
 *
 *省略写法:注解里面value属性值可以省略不写,对象名默认值是类名称,首字母小写(UserService -- userService)
 *   @Component    连括号都不写
 */

@Service //4个注解可以混用,都可以实现对象创建。只不过可以更好的见名之意
public class UserService {

    public void add() {
        System.out.println("service add.......");

    }
}

第四步:编写测试类进行测试:
在这里插入图片描述

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.config.SpringConfig;
import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testService1() {
        ApplicationContext context
                = new ClassPathXmlApplicationContext("bean1.xml");
        //之前是在xml配置的bean别名,现在是注解的value值,默认类名首字母小写
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }

}

总结:注解方式创建对象执行流程,首先加载配置文件,在配置文件中配置了开启组件扫描,此时spring就知道使用的是注解方式,之后找到配置的包中所有类, 如果类上有相关注解描述,则会根据注解创建对象,在之后就可以使用对象了。

开启组件扫描细节配置:
说明:更加细致的配置哪些类进行扫描,那些类不需要扫描。
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
   

    <!--示例 1
    use-default-filters="false" 表示现在不使用默认filter,自己配置 filter。不写默认是扫描包下所有的类。
    context:include-filter ,设置扫描哪些内容。
    annotation   Controller  :表示只扫描包中带这个注解Controller的类。
-->
    <context:component-scan base-package="com.atguigu" use-default-filters="false">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--示例 2
        下面配置扫描包所有内容
        context:exclude-filter: 设置哪些内容不进行扫描。   即 :只扫描除了Controller注解描述的类
    -->
    <context:component-scan base-package="com.atguigu">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>
2.3.9.2 注解方式 注入属性(对象类型)

说明

  1. @Autowired:默认按照类型注入,类型相同按照名称注入
    • 可以用在属性,方法,构造方法,set方法,参数,可以和@Qualifier注解搭配使用。
    • @Qualifier:如果类型相同,可以指定对应的名称注入,和@Autowired搭配使用。
    • Spring提供的注解
  2. @Resource:默认按照名称注入,如果名称相同,则在根据类型注入。
    • 可以直接在注解中写注入的名称,按照指定的名称注入。
    • 用在属性,set方法上
    • java规范提供的注解

测试一 @Autowired:在属性上

步骤1) 在 service 类和 dao 类上添加注解来创建对象

注意:如果是接口要在它的实现类上加注解。

UserService类:

package com.atguigu.spring5.service;

import org.springframework.stereotype.Service;


@Service
public class UserService {

    public void add() {
        System.out.println("service add.......");

    }
}

UserDao接口:

package com.atguigu.spring5.dao;

public interface UserDao {
    public void add();
}

UserDaoImpl实现类:

package com.atguigu.spring5.dao;

import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("dao add.....");
    }
}

bean1.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!--开启组件扫描
       方式1 如果扫描多个包,多个包使用逗号隔开
       方式2 扫描包上层目录
    -->
    <!--<context:component-scan base-package="com.atguigu.spring5.dao,com.atguigu.spring5.service"></context:component-scan>-->
    <context:component-scan base-package="com.atguigu.spring5"></context:component-scan>



</beans>

步骤二) 在 service 中注入 dao 对象,在 service 类添加 dao 类型属性,在属性上面使用注解。
在这里插入图片描述

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class UserService {
    //定义dao类型属性
    //不需要添加set方法,因为这个过程底层帮你封装了。
    //添加注入属性注解
      @Autowired  //根据类型进行注入(用的是父接口的名字,相当于多态方式创建对象)
      private UserDao userDao;



    public void add() {
        System.out.println("service add.......");
        userDao.add();

    }
}

步骤三) 在测试类中调用进行测试。

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testService1() {
        ApplicationContext context
                = new ClassPathXmlApplicationContext("bean1.xml");
        //之前是在xml配置的bean别名,现在是注解的value值,默认类名首字母小写
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }



}

在这里插入图片描述

测试二 @Qualifier:

说明:这个@Qualifier 注解的使用,和上面@Autowired 一起配合使用

应用场景:一个接口如果有多个实现类,类型都是相同的无法通过类型进行区分注入,此时就可以根据名称进行区分注入了。

为什么会出现这样的问题???
因为:我们接收的属性类型是父接口,相当于使用多态形式创建对象,好处是解耦。但是一个接口可以有多个实现类,这样它就无法区分使用的是哪个具体的实现类了。

测试:
1.修改UserService:
在这里插入图片描述

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;


@Service
public class UserService {
    //定义dao类型属性
    //不需要添加set方法,因为这个过程底层帮你封装了。
    //添加注入属性注解
      @Autowired  //根据类型进行注入
      @Qualifier(value = "userDaoImpl1") //根据名称进行注入
      private UserDao userDao;


    public void add() {
        System.out.println("service add.......");
        userDao.add();

    }
}

2.修改UserDaoImpl
在这里插入图片描述

package com.atguigu.spring5.dao;

import org.springframework.stereotype.Repository;

@Repository(value = "userDaoImpl1")//不写默认类名首字母小写
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("dao add.....");
    }
}

运行测试:仍然可以正确输出。其它文件同上,没有发生变化。
在这里插入图片描述

测试三 @Resource:可以根据名称注入,也可以根据类型注入

注意:这个是javax.annotation.Resource包下的注解。

在这里插入图片描述

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserService {

    //@Resource  //不写参数,根据默认名称行注入
    @Resource(name = "userDaoImpl1")  //根据指定名称进行注入
    private UserDao userDao;


    public void add() {
        System.out.println("service add.......");
        userDao.add();

    }
}

运行测试:仍然可以正确输出。其它文件同上,没有发生变化。
在这里插入图片描述

2.3.9.3 注解方式 注入属性(普通类型)
  • @Value:注入普通类型属性

在这里插入图片描述

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class UserService {


    @Value(value = "abc")//可以把abc注入到name属性中去
    private String name;


    public void add() {
        System.out.println("service add......."+name);
        userDao.add();

    }
}

运行测试:仍然可以正确输出。其它文件同上,没有发生变化。

在这里插入图片描述

2.3.9.4 完全注解开发(配置类)

说明:使用注解开发虽然简写了xml文件方式配置对象和属性,但是仍然需要在xml中进行配置开启组件扫描。如果是只想要使用注解进行配置,一点都不用xml文件该如何办呢???

:可以通过配置类的方式,代替xml文件。

(1)创建配置类,替代xml 配置文件

package com.atguigu.spring5.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration  //作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.atguigu"})//开启组件扫描,实际开发中可以使用springboot进一步简化。
public class SpringConfig {

}

(2)编写测试类

package com.atguigu.spring5.testdemo;

import com.atguigu.spring5.config.SpringConfig;
import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestSpring5Demo1 {

    @Test
    public void testService2() {
        //加载配置类
        ApplicationContext context
                = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();
    }


}

运行测试:仍然可以正确输出。其它文件同上,没有发生变化。
在这里插入图片描述

3. AOP

3.1 概念

(1)面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。

(2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能,可以降低耦合性。

(3)使用登录例子说明 AOP(有点类似于过滤器):把权限管理单独的设置为一个模块独立出去,然后通过配置的方式把它配置到登录的主干部分 如 成功分支,这样做的好处是:

  1. 不通过修改源代码方式,在主干功能里面添加新功能,可以降低耦合性。
  2. 现在不管有没有权限管理模块,程序都可以正常的执行。如果将来不需要权限管理,可以把这个模块去掉。

在这里插入图片描述

3.2 AOP(底层原理)

3.2.1 AOP 底层使用动态代理

说明:有两种情况的动态代理(默认)

第一种 有接口情况,使用 JDK 动态代理

  • 创建接口实现类的代理对象,来增强类中的方法
  • 解释:子类实现父接口,在子类的登录方法中做登录功能,现在想要在不修改源代码的情况下,在实现类的登录方法中添加新功能。使用jdk动态代理,会创建一个新的父接口实现类对象,即:代理对象(不是new出来的对象),代理对象的作用和原先的接口实现类对象(UserDaoImpl)作用一致(可以看成一个对象)。同一个对象当然有之前的功能也可以添加新的功能了。
  • 简略解释:创建一个新的接口实现类对象,2个对象可以看成是同一个对象,同一个对象当然有之前的功能也可以添加新的功能了。
    在这里插入图片描述

第二种 没有接口情况,使用 CGLIB 动态代理

  • 创建子类的代理对象,增强类的方法
  • 解释:子类继承父类,在子类的添加方法中增强一个新功能,那么可以使用CGLIB 动态代理,创建一个新的子类对象(即:代理对象:不是new出来的),这个代理对象和原先的子类对象Person作用相同(可以看成是同一个对象),同一个对象当然既有原来的功能也可以添加新的功能了。
  • 简略解释:同上,新的子类对象(代理对象)和原来的子类对象功能相同,可以看成是一个对象,同一个对象当然既有原来的功能也可以添加新的功能了。
  • JDK 动态代理和CGLIB 动态代理区别:一个是父接口,一个是父类。
    在这里插入图片描述

3.2.2 测试:原生方式 实现JDK 动态代理 (重听)

说明:现在使用的是Spring框架,框架底层已经帮你封装好了动态代理的代码,你只需要简单地配置下就可以使用了。

步骤一:使用 Proxy 类里面的方法创建代理对象
在这里插入图片描述
(1)调用 newProxyInstance 方法:方法有三个参数

在这里插入图片描述

  • 参数1:类加载器
  • 参数2:增强方法所在的类,这个类实现的接口,支持多个接口
  • 参数3:实现这个接口 InvocationHandler,创建代理对象,写增强的部分

步骤二:编写 JDK 动态代理代码

(1)创建接口,定义方法

package com.atguigu.spring5;

public interface UserDao {
    public int add(int a,int b);
    public String update(String id);
}

(2)创建接口实现类,实现方法

package com.atguigu.spring5;

public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {
        System.out.println("add方法执行了.....");
        return a+b;
    }

    @Override
    public String update(String id) {
        System.out.println("update方法执行了.....");
        return id;
    }
}

(3)使用 Proxy 类创建接口代理对象

package com.atguigu.spring5;

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

public class JDKProxy {

    public static void main(String[] args) {
        //创建接口实现类代理对象
        Class[] interfaces = {UserDao.class};

        //方式一:可以使用匿名实现类的匿名对象
//        Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                return null;
//            }
//        });
        //方式二:自己定义一个类
        UserDaoImpl userDao = new UserDaoImpl();
        //参数1:类加载器
        //参数2:增强方法所在的类,这个类实现的接口,支持多个接口
        //参数3:实现这个接口 InvocationHandler,创建代理对象,写增强的部分
        //返回代理对象
        UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result:"+result);
    }
}

//创建代理对象代码, 解释:只要UserDaoProxy代理对象被创建就会调用invoke方法
class UserDaoProxy implements InvocationHandler {

    //1 把创建的是谁的代理对象,把谁传递过来   此时是UserDaoImpl,为了更通用使用object类型来接收
    //有参数构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    //invoke方法写增强的逻辑
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //方法之前
        System.out.println("方法之前执行...."+method.getName()+" :传递的参数..."+ Arrays.toString(args));

        //被增强的方法执行
        Object res = method.invoke(obj, args);

        //方法之后
        System.out.println("方法之后执行...."+obj);
        return res;
    }
}


在这里插入图片描述

说明:以上演示是Aop底层实现原理,真正使用时都是底层封装好了,我们只需要配置使用即可。

3.3 AOP(术语)

1、连接点类中所有可以被增强的方法
2、切入点类中具体是哪几个被增强的方法(可以是一个,多个)
3、通知(增强):被增强方法中新添加的功能代码(不是直接写在被增强方法中,而是写在增强方法中)
4、切面(动作):把新增的代码添加到被增强方法中的过程

在这里插入图片描述

3.4 AOP 操作(准备工作 切入点表达式)

1、Spring 框架一般都是基于 AspectJ 实现 AOP 操作
(1)什么是AspectJ???
答:AspectJ 不是 Spring框架的组成部分,而是一个单独的 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使用,进行 AOP 操作

2、基于 AspectJ 实现 AOP 操作
(1)基于 xml 配置文件实现
(2)基于注解方式实现(推荐)

3、在项目工程里面引入 AOP 相关依赖

在这里插入图片描述
4、切入点表达式
(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强(4个参数)
(2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )

举例 1:对 com.atguigu.dao.BookDao 类里面的 add 方法进行增强 (一个类中的add方法

说明:权限修饰符可以具体的写 如 public 也可以用*代表任意的修饰符,返回值类型可以省略,..表示方法中的参数也是任意的
execution(* com.atguigu.dao.BookDao.add(..))

举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强(一个类中所有的方法
execution(* com.atguigu.dao.BookDao.* (..))

举例 3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强(所有类中的所有方法
execution(* com.atguigu.dao.*.* (..))

3.5 AOP 操作(AspectJ 注解–推荐)

3.5.1 案例测试

1、创建类,在类里面定义方法

package com.atguigu.spring5.aopanno;

//被增强的类
public class User {
    public void add() {
        System.out.println("add......");
    }
}


2、创建增强类(编写增强逻辑)
(1)在增强类里面,创建方法,让不同方法代表不同通知类型

package com.atguigu.spring5.aopanno;

//增强的类
public class UserProxy {
    //前置通知
    public void before() {
        System.out.println("before.	");
    }
}

3、进行通知的配置
(3.1)在 spring 配置文件中,开启注解扫描(xml形式或者配置类)
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.atguigu.spring5.aopanno"></context:component-scan>

   
</beans>

(3.2)使用注解创建 User(被增强类对象)和 UserProxy 对象(增强类对象)
在这里插入图片描述
在这里插入图片描述

(3.3)在增强类上面添加注解 @Aspect
解释:在spring配置文件中配置好开启生成代理对象后,它会找到哪个类上被注解 @Aspect标识,之后就会为当前类生成一个代理对象。
在这里插入图片描述

(3.4)在 spring 配置文件中开启生成代理对象
在这里插入图片描述

 <!-- 开启Aspect生成代理对象  作用:找到类上有这个@Aspect注解描述,就会生成代理对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4、配置不同类型的通知

(4.1)在增强类的里面,作为通知方法上添加通知类型注解,注解中的参数为切入点表达式
在这里插入图片描述

package com.atguigu.spring5.aopanno;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//增强的类
@Component
@Aspect//生成代理对象
public class UserProxy {
    //前置通知
    //前置通知
    //@Before 注解表示作为前置通知  参数为:切入点表达式
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before.	");
    }
}

(4.2)编写测试类进行测试:

package com.atguigu.spring5.test;

import com.atguigu.spring5.aopanno.User;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop {

    @Test
    public void testAopAnno() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        User user = context.getBean("user", User.class);
        //调用目标方法add(),前置方法在目标方法执行之前执行,所以最终的方法是
        //  先执行前置方法,在执行目标方法。
        user.add();
    }
}

在这里插入图片描述
(4.3)测试剩下的几个通知

package com.atguigu.spring5.aopanno;

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

//增强的类
@Component
@Aspect//生成代理对象
public class UserProxy {

    //前置通知  在目标方法执行之前执行
    //@Before 注解表示作为前置通知  参数为:切入点表达式
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before.	");
    }

    //后置通知(返回通知)  在目标方法 返回值结果之后 执行   目标方法有异常不在执行
    @AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning	");
    }
    //最终通知     在目标方法的 执行之后 执行   目标方法不管有没有异常都执行
    @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after.	");
    }
    //异常通知  目标方法有异常执行
    @AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing.	");
    }
    //环绕通知 在目标方法前后都可以执行
    @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前	");
        //注意:只有环绕通知才可以控制目标方法的执行
        proceedingJoinPoint.proceed(); //通过proceedingJoinPoint对象调用目标方法执行
        System.out.println("环绕之后	");
    }
}

在这里插入图片描述
(4.4)测试异常通知,有异常后才执行。并且后置通知不会执行,环绕通知的后面不会执行。
在这里插入图片描述
在这里插入图片描述

3.5.2 相同的切入点抽取

说明:相同的切入点表达式可以进行抽取,好处是将来如果改变只需要改变一处即可。
在这里插入图片描述

package com.atguigu.spring5.aopanno;

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

//增强的类
@Component
@Aspect//生成代理对象
public class UserProxy {
    //相同切入点抽取:定义一个方法 名字随意,使用@Pointcut注解描述,值为抽取的路径
    //    之后在具体使用的切入点表达式中使用方法名调用即可
    @Pointcut(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void pointdemo() {

    }

    //前置通知  在目标方法执行之前执行
    //@Before 注解表示作为前置通知  参数为:切入点表达式
    @Before(value = "pointdemo()")// 值为抽取的方法名
    public void before() {
        System.out.println("before.	");
    }

    //后置通知(返回通知)  在目标方法返回值结果之后执行   目标方法有异常不在执行
    @AfterReturning(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("afterReturning	");
    }
    //最终通知     在目标方法的执行之后执行   目标方法不管有没有异常都执行
    @After(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void after() {
        System.out.println("after.	");
    }
    //异常通知  目标方法有异常执行
    @AfterThrowing(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterThrowing() {
        System.out.println("afterThrowing.	");
    }
    //环绕通知 在目标方法前后都可以执行
    @Around(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前	");
        //注意:只有环绕通知才可以控制目标方法的执行
        proceedingJoinPoint.proceed(); //通过proceedingJoinPoint对象调用目标方法执行
        System.out.println("环绕之后	");
    }
}

仍然执行成功:
在这里插入图片描述

3.5.3 设置增强类优先级

说明:有多个增强类同一个方法进行增强,设置增强类优先级。

(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高

目标方法之前的通知方法:数字小的先执行

目标方法之后的通知方法:数字小的后执行

编写PersonProxy 类:并设置优先级
在这里插入图片描述

package com.atguigu.spring5.aopanno;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Aspect
@Order(1)
public class PersonProxy {
    //后置通知(返回通知)
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void afterReturning() {
        System.out.println("Person Before.........");
    }
}

在原来的类上设置优先级:
在这里插入图片描述
测试:数字越小,优先级越高的先执行。
在这里插入图片描述

3.5.4 完全使用注解开发(配置类)

(1)创建配置类,不需要创建 xml 配置文件

注意:代替的是xml配置文件。

package com.atguigu.spring5.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration//表示配置类,代替xml文件
@ComponentScan(basePackages = {"com.atguigu"})//开启组件(注解)扫描
//开启Aspect生成代理对象  作用:找到类上有这个@Aspect注解描述,就会生成代理对象   默认为false
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

说明:使用IOC注解方式开发需要在xml中配置,组件(注解)扫描。
     使用AOP注解方式动态代理需要在xml中配置,组件扫描 和 开启Aspect生成代理对象
     
所以,如果是IOC完全注解开发 只需要在配置类中使用 配置类注解和组件扫描注解即可
     如果是AOP完全注解开发,除了配置类注解和组件扫描注解还要使用生成代理对象注解

3.6 AOP 操作(AspectJ xml配置文件–不推荐)

1、创建两个类,增强类和被增强类,创建方法

package com.atguigu.spring5.aopxml;

//被增强的类
public class Book {
    public void buy() {
        System.out.println("buy.............");
    }
}

package com.atguigu.spring5.aopxml;

//增强类
public class BookProxy {
    public void before() {
        System.out.println("before.........");
    }
}

2、在 spring 配置文件中创建两个类对象
JdbcTemplate(概念和准备)
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
     <!--创建对象-->
    <bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>

    
</beans>

3、在 spring 配置文件中配置切入点
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
 
   <!--配置 aop 增强-->
    <aop:config>
        <!--切入点-->
        <aop:pointcut id="p" expression="execution(* com.atguigu.spring5.aopxml.Book.buy(..))"/>
        <!--配置切面-->
        <aop:aspect ref="bookProxy">
            <!--增强作用在具体的方法上-->
            <aop:before method="before" pointcut-ref="p"/>
        </aop:aspect>
    </aop:config>
</beans>

编写测试类进行测试:
在这里插入图片描述

package com.atguigu.spring5.test;

import com.atguigu.spring5.aopanno.User;
import com.atguigu.spring5.aopxml.Book;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAop {

 
    @Test
    public void testAopXml() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }
}

4. JdbcTemplate(概念和准备)

4.1 什么是 JdbcTemplate

概述:Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作
Template:模板

4.2 准备工作

(1)引入相关 jar 包
在这里插入图片描述
(2)在 spring 配置文件配置数据库连接池

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>
</beans>

(3)在xml文件中创建 JdbcTemplate 对象,注入 DataSource

<!-- JdbcTemplate 对象 --> 
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 
    <!--注入 dataSource--> 
    <property name="dataSource" ref="dataSource"></property> 
</bean> 

(4)创建 service 类,创建 dao 类,在 dao 注入 jdbcTemplate 对象

  • 配置文件
    在这里插入图片描述
<!-- 组件扫描 -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>
  • Service
package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BookService {
    //注入dao
    @Autowired
    private BookDao bookDao;

}

  • BookDao
package com.atguigu.spring5.dao;

public interface BookDao {
}

  • BookDaoImpl
package com.atguigu.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements BookDao{
    //注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

目录结构:
在这里插入图片描述

4.3 JdbcTemplate 操作数据库(添加)

1、对应数据库创建实体类

package com.atguigu.spring5.entity;

public class Book{
    private String userId;
    private String username;
    private String ustatus;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getUstatus() {
        return ustatus;
    }

    public void setUstatus(String ustatus) {
        this.ustatus = ustatus;
    }
}

2、编写 service 和 dao
(1) 进行数据库添加操作
在这里插入图片描述

  //添加的方法
    public void addBook(Book book){

        bookDao.add(book);
    }

在这里插入图片描述

//添加的方法
     void add(Book book);

(2)调用 JdbcTemplate 对象里面 update 方法实现添加操作
在这里插入图片描述

  • 有两个参数
  • 第一个参数:sql 语句
  • 第二个参数:可变参数,设置 sql 语句值
    在这里插入图片描述
 //添加的方法
    @Override
    public void add(Book book) {
        //1 创建 sql 语句
        String sql = "insert into t_book values(?,?,?)";
        //2 调用方法实现
        Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

3、测试类

package com.atguigu.spring5.test;

import com.atguigu.spring5.entity.Book;
import com.atguigu.spring5.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBook {


    @Test
    public void testJdbcTemplate() {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book();
        book.setUserId("1");
        book.setUsername("java");
        book.setUstatus("a");
        bookService.addBook(book);
    }
}

在这里插入图片描述

在这里插入图片描述

4.4 JdbcTemplate 操作数据库(修改和删除)

1、修改
2、删除
在这里插入图片描述

    //修改的方法
    public void updateBook(Book book){

        bookDao.updateBook(book);
    }
    //删除的方法
    public void deleteBook(String id){

        bookDao.deleteBook(id);
    }

在这里插入图片描述

	//修改
    void updateBook(Book book);
    //删除
    void deleteBook(String id);

在这里插入图片描述

    //修改
    @Override
    public void updateBook(Book book) {
        String sql = "update t_book set username=?,ustatus=? where user_id=?";
        Object[] args = {book.getUsername(), book.getUstatus(),book.getUserId()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }
    //删除
    @Override
    public void deleteBook(String id) {
        String sql = "delete from t_book where user_id=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

测试类:

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBook {


    @Test
    public void testJdbcTemplate() {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
       
          //修改
//        Book book = new Book();
//        book.setUserId("1");
//        book.setUsername("javaqqq");
//        book.setUstatus("aqqq");
//        bookService.updateBook(book);

        //删除
        bookService.deleteBook("1");
    }

}

在这里插入图片描述

4.5 JdbcTemplate 操作数据库(查询返回某个值)

1、查询表里面有多少条记录,返回是某个值
2、使用 JdbcTemplate 实现查询返回某个值代码
在这里插入图片描述

  • 有两个参数
  • 第一个参数:sql 语句
  • 第二个参数:返回类型 Class
    在这里插入图片描述
  //查询表记录数
    public int findCount(){
        int count = bookDao.selectCount();
        return count;
    }

在这里插入图片描述

 //查询表记录数
    int selectCount();

在这里插入图片描述

//查询表记录数
    @Override
    public int selectCount() {
        String sql = "select count(*) from t_book";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

测试类:
在这里插入图片描述

 //查询返回某个值
 int count = bookService.findCount();
 System.out.println(count);

在这里插入图片描述

4.6 JdbcTemplate 操作数据库(查询返回对象)

1、场景:查询图书详情
2、JdbcTemplate 实现查询返回对象
在这里插入图片描述

  • 有三个参数
  • 第一个参数:sql 语句
  • 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
  • 第三个参数:sql 语句中的?值
    测试:
    Book类中添加toString方法:在这里插入图片描述
    BookService类:
    在这里插入图片描述
 //查询返回对象
    public Book findOne(String id){
        Book book = bookDao.findBookInfo(id);
        return book;
    }

BookDao接口:
在这里插入图片描述

 //查询返回对象
    Book findBookInfo(String id);

BookDaoImpl实现类:
在这里插入图片描述

 //查询返回对象
    @Override
    public Book findBookInfo(String id) {
        String sql = "select * from t_book where user_id=?";
        //调用方法
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }

测试类TestBook:
在这里插入图片描述

 //查询返回某个对象
 Book book = bookService.findOne("1");
 System.out.println(book);

4.7 JdbcTemplate 操作数据库(查询返回集合对象)

1、场景:查询图书列表分页…

2、调用 JdbcTemplate 方法实现查询返回集合

  • 有三个参数
  • 第一个参数:sql 语句
  • 第二个参数:RowMapper 是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
  • 第三个参数:sql 语句?值

BookService类:
在这里插入图片描述

 //查询返回集合对象
    public List<Book> findAll(){
        List<Book> book = bookDao.findAllBook();
        return book;
    }

BookDao接口:

在这里插入图片描述

//查询返回集合对象
    List<Book> findAllBook();

BookDaoImpl实现类:
在这里插入图片描述

 //查询返回集合对象
    @Override
    public List<Book> findAllBook() {
        String sql = "select * from t_book";
        //调用方法
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

测试类TestBook:
在这里插入图片描述

//查询返回集合对象
List<Book> list = bookService.findAll();
System.out.println(list);

在这里插入图片描述

4.8 JdbcTemplate 操作数据库(批量操作)

4.8.1 批量添加操作

(1)JdbcTemplate 实现批量添加操作
在这里插入图片描述

  • 有两个参数
  • 第一个参数:sql 语句
  • 第二个参数:List 集合,添加多条记录数据

BookService类:
在这里插入图片描述

//批量添加操作
    public void batchAdd(List<Object[]> batchAdd){
        bookDao.batchAddBook(batchAdd);
    }

BookDao接口:

在这里插入图片描述

 //批量添加操作
    void batchAddBook(List<Object[]> batchAdd);

BookDaoImpl实现类:
在这里插入图片描述

 //批量添加操作
    @Override
    public void batchAddBook(List<Object[]> batchAdd) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchAdd);
        System.out.println(Arrays.toString(ints));
    }

测试类TestBook:
在这里插入图片描述

 //批量添加测试
 List<Object[]> batchArgs = new ArrayList<>(); 
 Object[] o1 = {"3","java","a"};
 Object[] o2 = {"4","c++","b"};
 Object[] o3 = {"5","MySQL","c"}; 
 batchArgs.add(o1); 
 batchArgs.add(o2); 
 batchArgs.add(o3);
 //调用批量添加
 bookService.batchAdd(batchArgs);

在这里插入图片描述

4.8.2 批量修改操作

BookService类:
在这里插入图片描述

 //批量修改操作
    public void batchUpdate(List<Object[]> batchAdd){
        bookDao.batchUpdateBook(batchAdd);
    }

BookDao接口:

在这里插入图片描述

//批量修改操作
void batchUpdateBook(List<Object[]> batchAdd);

BookDaoImpl实现类:
在这里插入图片描述

 //批量修改操作
 @Override
 public void batchUpdateBook(List<Object[]> batchAdd) {
     String sql = "update t_book set username=?,ustatus=? where user_id=?";
     int[] ints = jdbcTemplate.batchUpdate(sql, batchAdd);
     System.out.println(Arrays.toString(ints));
 }

测试类TestBook:
在这里插入图片描述

//批量修改
List<Object[]> batchArgs = new ArrayList<>(); 
Object[] o1 = {"java0909","a3","3"};
Object[] o2 = {"c++1010","b4","4"};
Object[] o3 = {"MySQL1111","c5","5"}; 
batchArgs.add(o1);
batchArgs.add(o2); 
batchArgs.add(o3);
//调用方法实现批量修改
bookService.batchUpdate(batchArgs);

在这里插入图片描述

4.8.3 批量删除操作

BookService类:
在这里插入图片描述

 //批量删除
 public void batchDelete(List<Object[]> batchAdd){
     bookDao.batchDeleteBook(batchAdd);
 }

BookDao接口:

在这里插入图片描述

//批量删除
void batchDeleteBook(List<Object[]> batchAdd);

BookDaoImpl实现类:
在这里插入图片描述

 //批量删除
 @Override
 public void batchDeleteBook(List<Object[]> batchAdd) {
     String sql = "delete from t_book where user_id=?";
     int[] ints = jdbcTemplate.batchUpdate(sql, batchAdd);
     System.out.println(Arrays.toString(ints));
 }

测试类TestBook:
在这里插入图片描述

//批量删除
List<Object[]> batchArgs = new ArrayList<>();
Object[] o1 = {"3"};
Object[] o2 = {"4"};
batchArgs.add(o1);
batchArgs.add(o2);
//调用方法实现批量删除
bookService.batchDelete(batchArgs);

在这里插入图片描述

5. 事务操作

5.1 事务概念

1、什么事务
(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败
(2)典型场景:银行转账

  • lucy 转账 100 元 给 mary
  • lucy 少 100,mary 多 100

2、事务四个特性(ACID)
(1)原子性
(2)一致性
(3)隔离性
(4)持久性

5.2 搭建事务操作环境

在这里插入图片描述
1、创建数据库表,添加记录

在这里插入图片描述
2、创建 service,搭建 dao,完成对象创建和注入关系

(1)service 注入 dao,在 dao 注入 JdbcTemplate,在 JdbcTemplate 注入 DataSource

bean1.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 组件扫描 -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!-- 创建数据库连接池对象 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!-- 创建JdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>


</beans>

UserService类:

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;
}

UserDao接口:

package com.atguigu.spring5.dao;

public interface UserDao {

}

UserDaoImpl实现类:

package com.atguigu.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

3、在 dao 创建两个方法:多钱和少钱的方法,在 service 创建方法(转账的方法)

UserService类:

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
        //lucy 少 100
        userDao.reduceMoney();

        //mary 多 100
        userDao.addMoney();
    }

}

UserDao接口:

package com.atguigu.spring5.dao;

public interface UserDao {
    //多钱
    public void addMoney();
    //少钱
    public void reduceMoney();
}


UserDaoImpl实现类:

package com.atguigu.spring5.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //lucy转账100给mary
    //少钱
    @Override
    public void reduceMoney() {
        String sql = "update t_account set money=money-? where username=?";
        jdbcTemplate.update(sql,100,"lucy");
    }

    //多钱
    @Override
    public void addMoney() {
        String sql = "update t_account set money=money+? where username=?";
        jdbcTemplate.update(sql,100,"mary");
    }
}

测试类TestBook :

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestBook {


    @Test
    public void testAccount() {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }



}



在这里插入图片描述

在这里插入图片描述
4、上面代码,如果正常执行没有问题的,但是如果代码执行过程中出现异常,有问题
(1)还原数据库表中的数据:
在这里插入图片描述
(2)模拟异常:
在这里插入图片描述
(3)再次运行测试类:可以看到lucy钱少了,mary有没有收到钱,显然不合理。
在这里插入图片描述

5、上面问题如何解决呢?

答:使用事务进行解决

6、事务操作过程

在这里插入图片描述

package com.atguigu.spring5.service;

import com.atguigu.spring5.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    //注入 dao
    @Autowired
    private UserDao userDao;

    //转账的方法
    public void accountMoney() {
       try{
        //第一步 开启事务

        //第二步 进行业务操作
        //lucy少100
        userDao.reduceMoney();

        //模拟异常
        int i = 10/0;

        //mary多100
        userDao.addMoney();

        //第三步 没有发生异常,提交事务
        }catch(Exception e) {
        //第四步 出现异常,事务回滚
        }
    }

}


5.3 Spring 事务管理介绍

5.3.1 事务添加位置

说明:事务添加到 JavaEE 三层结构里面 Service 层(业务逻辑层)

解释:理论上添加到哪一层都可以,但是都建议添加在Service层,因为在service层会调用不同的dao操作(清晰地知道你是干啥业务的),这样更加准确。

5.3.2 Spring 进行事务管理操作的分类

有两种方式

  1. 编程式事务管理 :即通过代码一步一步的实现。
    缺点:每次使用事务都要编写相同的代码步骤,太过繁琐。
    在这里插入图片描述
  2. 声明式事务管理(推荐)

5.3.3 声明式事务 管理 实现方式

  1. 基于注解方式(推荐)
  2. 基于 xml 配置文件方式

5.3.4 声明式事务管理 底层原理`

在 Spring 进行声明式事务管理,底层使用 AOP 原理

5.3.5 Spring 事务管理 API

(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类

如:jdbc Template模板,mybatis,hibernate使用对应的事务实现类。
jdbc Template模板,mybatis- - -》DataSourceTransactionManager
hibernate- - -》HibernateTransactionManaeger
在这里插入图片描述

5.4 事务操作(声明式事务的注解方式)

5.4.1 基本使用步骤

1、在 spring 配置文件配置事务管理器
在这里插入图片描述

 <!--创建事务管理器对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

2、在 spring 配置文件,开启事务注解
(1)在 spring 配置文件引入名称空间 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:aop="http://www.springframework.org/schema/aop" 
       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 http://www.springframework.org/schema/context/spring-context.xsd 
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd 
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> 

(2)开启事务注解
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 开启组件(注解)扫描 -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!-- 创建数据库连接池对象 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!-- 创建JdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--创建事务管理器对象-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>



</beans>

3、在 service 类上面(或者 service 类里面方法上面)添加事务注解
(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务
在这里插入图片描述
4、再次运行测试类,发现因为提交时有异常数据会进行回滚,数据库里面的数据也应该回滚到最初的状态。
在这里插入图片描述

5.4.2 声明式事务管理 参数配置

1、在 service 类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数
在这里插入图片描述
2、propagation:事务传播行为
(1)多事务方法直接进行调用,这个过程中事务 是如何进行管理的
(2)不配置默认就是:REQUIRED
在这里插入图片描述
在这里插入图片描述
3、ioslation:事务隔离级别
(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读

(3)脏读:一个未提交事务读取到另一个未提交事务的数据
在这里插入图片描述

(4)不可重复读:一个未提交事务读取到另一提交事务修改数据
在这里插入图片描述

(5)幻读:一个未提交事务读取到另一提交事务添加数据

类似不可重复读。

(6)解决:通过设置事务隔离级别,解决读问题
说明:如果用的数据库是mysql那么此时并设置默认的隔离级别就是:REPEATABLE READ
在这里插入图片描述
4、timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1(代表不超时) ,设置时间以秒单位进行计算

5、readOnly:是否只读
(1)读:查询操作,写:添加修改删除操作
(2)readOnly 默认值 false,表示可以查询,可以添加修改删除操作
(3)设置 readOnly 值是 true,设置成 true 之后,只能查询

6、rollbackFor:回滚
(1)设置出现哪些异常进行事务回滚

7、noRollbackFor:不回滚
(1)设置出现哪些异常不进行事务回滚

在这里插入图片描述

5.6.3 完全注解 声明式 事务管理

1、创建配置类,使用配置类替代 xml 配置文件
在这里插入图片描述

package com.atguigu.spring5.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration //配置类,代替xml
@ComponentScan(basePackages = "com.atguigu") //开启组件(注解)扫描
@EnableTransactionManagement //开启事务注解
public class TxConfig {
     //说明:实际开发中使用的springboot方式
    //创建数据库连接池对象
    @Bean
    public DruidDataSource getDruidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql:///user_db");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

    //创建JdbcTemplate对象
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
        //到ioc容器中根据类型找到dataSource
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        //注入dataSource
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    //创建事务管理器对象
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DataSource dataSource) {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}

2、打开注解方式
在这里插入图片描述
3、再次运行测试类,发现因为提交时有异常数据会进行回滚,数据库里面的数据也应该回滚到最初的状态:
在这里插入图片描述

   @Test
    public void testAccount2() {

        ApplicationContext context =
                new AnnotationConfigApplicationContext(TxConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }

在这里插入图片描述

5.5 事务操作(XML 声明式事务管理)

1、在 spring 配置文件中进行配置
第一步 配置事务管理器
第二步 配置通知
第三步 配置切入点和切面
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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 http://www.springframework.org/schema/context/spring-context.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
                        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 组件扫描 -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!-- 数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql:///user_db" />
        <property name="username" value="root" />
        <property name="password" value="root" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>

    <!-- JdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <!--注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--1 创建事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--2 配置通知-->
    <tx:advice id="txadvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指定哪种规则的方法上面添加事务-->
            <tx:method name="accountMoney" propagation="REQUIRED"/>
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>

    <!--3 配置切入点和切面-->
    <aop:config>
        <!--配置切入点-->
        <aop:pointcut id="pt" expression="execution(* com.atguigu.spring5.service.UserService.*(..))"/>
        <!--配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>
</beans>

测试:
把注解方式注释掉:
在这里插入图片描述
再次运行测试类,发现因为提交时有异常数据会进行回滚,数据库里面的数据也应该回滚到最初的状态:
在这里插入图片描述

 @Test
    public void testAccount1() {

        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.accountMoney();
    }

在这里插入图片描述

6. Spring5 框架新功能

6.1 支持的jdk版本说明

整个 Spring5 框架的代码基于 Java8,运行时兼容 JDK9,许多不建议使用的类和方法在代码库中删除。

6.2 Spring5 框架整合Log4j2 日志框架

日志:通过日志可以更好的查看程序的执行过程,另外通过日志可以更好的排查问题

Spring 5.0 框架自带了通用的日志封装,但是也能整合别的日志工具如: Log4j2

(1)Spring5 已经移除 Log4jConfigListener,官方建议使用 Log4j2 。想用之前的日志需要降低Spring版本。(如:想要使用Log4j,需要使用Spring4)

(2)Spring5 框架整合 Log4j2

第一步引入jar 包

在这里插入图片描述

第二步 创建 log4j2.xml 配置文件,注意这个配置文件名字为固定写法。
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL 越往右输出的内容就越多。-->
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4j2内部各种详细输出-->
<configuration status="INFO">
    <!--先定义所有的appender-->
    <appenders>
        <!--输出日志信息到控制台-->
        <console name="Console" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </console>
    </appenders>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>

测试1:
找到之前的测试方法进行测试:可以看到在控制台输出的日志格式为xml文件配置的格式。
在这里插入图片描述
测试2:
修改为DEBUG 级别可以看到更多的日志信息。
在这里插入图片描述

在这里插入图片描述
测试3:还可以手动输出日志到控制台。
说明

  1. 之前都是运行程序,Spring框架的过程自动在控制台输出的日志,还可以手动进行日志输出到控制台。
  2. 代替sout输出信息到控制台,使用日志输出。
package com.atguigu.spring5.test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserLog {
                                                             //当前类.class
    private static final Logger log = LoggerFactory.getLogger(UserLog.class);

    public static void main(String[] args) {

        log.info("hello log4j2");
        log.warn("hello log4j2");
    }
}

在这里插入图片描述

6.3 Spring5 框架核心容器支持@Nullable 注解

(1)@Nullable 注解可以使用在方法上面,属性上面,方法参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空。即:不加注解可能会报空指针异常,加上之后表示可以为空。

(2)注解用在方法上面,方法返回值可以为空
在这里插入图片描述
(3)注解使用在方法参数里面,方法参数可以为空
在这里插入图片描述
(4)注解使用在属性上面,属性值可以为空

在这里插入图片描述

6.4 Spring5 核心容器 支持函数式风格(GenericApplicationContext)

说明:函数式风格就是jdk1.8新特性中的Lambda 表达式写法。

User类:

package com.atguigu.spring5.test;

public class User {

}

测试类:

  //函数式风格创建对象,交给spring进行管理
    @Test
    public void testGenericApplicationContext() {
        //1 创建GenericApplicationContext对象
        GenericApplicationContext context = new GenericApplicationContext();
        //2 调用context的方法对象注册
        context.refresh();
        context.registerBean("user1",User.class,() -> new User());
        //3 获取在spring注册的对象
        // User user = (User)context.getBean("com.atguigu.spring5.test.User");
        User user = (User)context.getBean("user1");
        System.out.println(user);
    }

在这里插入图片描述

6.5 Spring5 支持整合JUnit4和5单元测试框架

注意:java基础是单元测试方法,这个地方是整合单元测试框架。

6.5.1 整合 JUnit4

第一步 引入 Spring 相关针对测试依赖
在这里插入图片描述
在这里插入图片描述

第二步 创建测试类,使用注解方式完成。

说明:可以使用注解方式代替之前的读取配置文件获取对象的操作(即,在测试方法中加载配置文件的代码)。

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class) //单元测试框架版本
@ContextConfiguration("classpath:bean1.xml") //加载配置文件
public class JTest4 {

    @Autowired //直接注入UserService 对象
    private UserService userService;

    @Test
    public void test1() {
        userService.accountMoney();
    }
}

在这里插入图片描述

6.5.2 整合 JUnit5

第一步 引入 JUnit5 的 jar 包

在这里插入图片描述
第二步 创建测试类,使用注解完成
写法一:使用2个注解替换原来的juint4的注解。

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class JTest5 {

    @Autowired
    private UserService userService;

    @Test
    public void test1() {
        userService.accountMoney();
    }
}

写法二:使用一个复合注解替代上面两个注解完成整合

package com.atguigu.spring5.test;

import com.atguigu.spring5.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:bean1.xml")
//还可以使用复合注解代替上面的2个注解
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JTest5 {

    @Autowired
    private UserService userService;

    @Test
    public void test1() {
        userService.accountMoney();
    }
}

在这里插入图片描述

6.6 Webflux (学完别的知识在听)

说明:想要学习Webflux要先进行掌握以下知识。
在这里插入图片描述

6.6.1 SpringWebflux 介绍

在这里插入图片描述

2、响应式编程(Java 实现)
3、响应式编程(Reactor 实现)
4、SpringWebflux 执行流程和核心 API
5、SpringWebflux(基于注解编程模型)
6、SpringWebflux(基于函数式编程模型)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值