Spring5框架

一、笔记基本内容

1.Spring 概念
2.IOC容器
(1)IOC底层原理
(2)IOC接口(BeanFactory)
(3)IOC操作Bean管理(基于xml)
(4)IOC操作Bean管理(基于注解)
3.Aop
4.JdbcTemplate
5.事务管理
6.Spring5新特性

二、Spring5框架概述

1、Spring是轻量级的开源的JavaEE框架
2、Spring可以解决企业应用开发的复杂性
3、Spring有两个核心部分:IOC和Aop
(1)IOC:控制反转,把创建对象过程交给Spring进行管理
(2)Aop:面向切面,不修改源代码进行功能增强
4、Spring特点
(1)方便解耦,简化开发
(2)Aop编程支持
(3)方便程序测试
(4)方便和其他框架进行整合
(5)方便进行事务操作
(6)降低API开发难度

三、Spring5入门案例

(1)使用Spring最新稳定版本5.2.6
在这里插入图片描述
(2)下载地址
https://repo.spring.io/release/org/springframework/spring/

在这里插入图片描述
在这里插入图片描述
2、打开idea工具,创建普通Java工程
在这里插入图片描述
在这里插入图片描述
3、导入Spring5相关jar包
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4、创建普通类,在这个类创建普通方法

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

5、创建Spring配置文件,在配置文件配置创建的对象
(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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!-- 配置User对象创建 -->
    <bean id="user" class="com.atguigu.spring5.User"></bean>
</beans>

6、进行测试代码编写

package com.atguigu.spring5.testdemo;

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

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

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

        System.out.println("user = " + user);
        user.add();
    }
}

在这里插入图片描述
IOC(概念和原理)

1、什么是IOC
(1)控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理
(2)使用IOC目的:为了耦合度降低
(3)做入门案例就是IOC实现
2、IOC底层原理
(1)xml解析、工厂模式、反射
3、画图讲解IOC底层原理
在这里插入图片描述
在这里插入图片描述
IOC(BeanFactory接口)
1、IOC思想基于IOC容器完成,IOC容器底层就是对象工厂
2、Spring提供IOC容器实现两种方式:(两个接口)
(1)BeanFactory:IOC容器基本实现,是Spring内部的使用接口,不提供开发人员进行使用
*加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象
(2)ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用
*加载配置文件时候就会把在配置文件对象进行创建
3、ApplicationContext接口有实现类
在这里插入图片描述
IOC操作Bean管理(概念)
1、什么是Bean管理
(0)Bean管理指的是两个操作
(1)Spring创建对象
(2)Spirng注入属性

2、Bean管理操作有两种方式
(1)基于xml配置文件方式实现
(2)基于注解方式实现

IOC操作Bean管理(基于xml方式)
1、基于xml方式创建对象
在这里插入图片描述
(1)在spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建
(2)在bean标签有很多属性,介绍常用的属性

  • id属性:唯一标识
  • class属性:类全路径(包类路径)
    (3)创建对象时候,默认也是执行无参数构造方法完成对象创建
    在这里插入图片描述
    在这里插入图片描述

2、基于xml方式注入属性
(1)DI:依赖注入,就是注入属性
3、第一种注入方式:使用set方法进行注入
(1)创建类,定义属性和对应的set方法

/**
 * 演示使用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;
    }
}

(2)在spring配置文件配置对象创建,配置属性注入

<!-- 2 set方法注入属性-->
    <bean id="book" class="com.atguigu.spring5.Book">
<!-- 使用property完成属性注入
    name: 类里面属性名称
    value:向属性注入的值
    -->
        <property name="bname" value="与基金"></property>
        <property name="bauthor" value="fff"></property>
    </bean>

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

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);
    }
}
<bean id="orders" class="com.atguigu.spring5.Orders">
        <constructor-arg name="oname" value="abc"></constructor-arg>
        <constructor-arg name="address" value="China"></constructor-arg>

    </bean>
@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);
        orders.ordersTest();
    }

5、p名称空间注入(了解)
(1)使用p名称空间注入,可以简化基于xml配置方式第一步添加p名称空间在配置文件中

<?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="book" class="com.atguigu.spring5.Book" p:bname="aaa" p:bauthor="djf">

    </bean>

四、IOC操作Bean管理(xml注入其他类型属性)

(一)直面量-null值

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


}

<bean id="book" class="com.atguigu.spring5.Book">
        <property name="bname" value="aaa"></property>
        <property name="bauthor" value="b"></property>
<!--        null值-->
        <property name="address">
            <null/>
        </property>
    </bean>
@Test
    public void testBook() {
        // 1 加载Spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean1.xml");

        // 2 获取配置创建的对象
        Book book = context.getBean("book", Book.class);
        System.out.println("book = " + book);
        book.testDemo();
    }

(二)直面量-属性值包含特殊符号

<!-- 属性值包含特殊符号
    1 把<>进行转义
    2 把带特殊符号内容写到 <![CDATA[ 内容 ]]>-->
    <bean id="book" class="com.atguigu.spring5.Book">
        <property name="address">
            <value>
                <![CDATA[<<南京>>]]>
            </value>
        </property>
    </bean>

(三)注入属性-外部bean

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

package com.atguigu.spring5.service;

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

public class UserService {

    // 创建UserDao类型属性,生成set方法
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

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

    }

}


<!--    1 创建service和dao对象创建-->
    <bean id="userService" class="com.atguigu.spring5.service.UserService">
<!--     注入userDao对象
         name属性:类里面属性名称
         ref属性:创建userDao对象bean标签id值-->
        <property name="userDao" ref="userDaoImpl"></property>
    </bean>
    <bean id="userDaoImpl" class="com.atguigu.spring5.dao.UserDaoImpl"></bean>

    @Test
    public void testAdd() {
        // 1 加载spring配置文件
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        // 2 获取配置创建的对象
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

(四)注入属性-内部bean

(1)一对多关系:部门和员工
一个部门有多个员工,一个员工属于一个部门部门是一,员工是多
(2)在实体类之间表示一对多关系,员工表示所属部门,使用对象类型属性进行表示

package com.atguigu.spring5.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);
    }
}

package com.atguigu.spring5.bean;

// 部门类
public class Dept {
    private String dname;

    public void setDname(String dname) {
        this.dname = dname;
    }

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

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

        // 2 获取配置创建的对象
        Emp emp = context.getBean("emp", Emp.class);
        emp.add();
    }
<?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.spring5.bean.Emp">
<!--设置两个普通属性-->
        <property name="ename" value="lycy"></property>
        <property name="gender" value="nv"></property>
<!--设置对象类型属性-->
        <property name="dept">
            <bean id="dept" class="com.atguigu.spring5.bean.Dept">
                <property name="dname" value="安保部"></property>
            </bean>
        </property>
</bean>
</beans>

(五)注入属性-级联赋值

第一种写法

<?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.spring5.bean.Emp">
<!--    设置两个普通属性-->
    <property name="ename" value="nv"></property>
    <property name="gender" value="nv"></property>
<!--    级联赋值-->
    <property name="dept" ref="dept"></property>
</bean>
    <bean id="dept" class="com.atguigu.spring5.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>

</beans>

第二种写法


<!--    级联赋值-->
<bean id="emp" class="com.atguigu.spring5.bean.Emp">
<!--    设置两个普通属性-->
    <property name="ename" value="nv"></property>
    <property name="gender" value="nv"></property>
<!--    级联赋值-->
    <property name="dept" ref="dept"></property>
    <property name="dept.dname" value="技术部"></property>
<!--    上面报红,要生成get方法-->
</bean>
    <bean id="dept" class="com.atguigu.spring5.bean.Dept">
        <property name="dname" value="财务部"></property>
    </bean>

五、IOC操作Bean管理(xml注入集合属性)

(一)注入数组类型属性

(二)注入List集合类型属性

(三)注入Map集合类型属性

(1)创建类,定义数组,list,map,set类型属性,生成对应set方法

package com.atguigu.spring5.collectiontype2;

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 setList(List<String> list) {
        this.list = list;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public void setCourses(String[] courses) {
        this.courses = courses;
    }
}

(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">
<!--集合类型属性注入-->
    <bean id="stu" class="com.atguigu.spring5.collectiontype2.Stu">
<!--        数组类型属性注入-->
        <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>

(4)在集合里面设置对象类型值

</bean>
    <!--创建多个course对象-->
    <bean id="course1" class="com.atguigu.spring5.collectiontype2.Course">
        <property name="cname" value="Spring5框架"></property>
    </bean>
    <bean id="course2" class="com.atguigu.spring5.collectiontype2.Course">
        <property name="cname" value="MyBatis框架"></property>
    </bean>
<!--         注入list集合类型,值是对象-->
        <property name="courseList">
            <list>
                <ref bean="course1"></ref>
                <ref bean="course2"></ref>
            </list>
        </property>
// 课程类
public class Course {
    private String cname; // 课程名称

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

    public void setCourseList(List<Course> courseList) {
        this.courseList = courseList;
    }

(五)把集合注入部分提取出来

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

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

</beans>

六、IOC操作Bean管理(FactoryBean)

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

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

public class MyBean implements FactoryBean<Course> {
    @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;
    }
}

@Test
    public void test3() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean3.xml");
        Course course = context.getBean("myBean", Course.class);
        System.out.println(course);
    }

七、IOC操作Bean管理(bean作用域)

1.在spring里面,设置创建bean实例是单实例还是多实例

2、在Spring里面,默认情况下,bean是单实例对象

在这里插入图片描述
3.如何设置单实例还是多实例
(1)在spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例
(2)scope属性值
第一个值默认值,singleton,表示是单实例对象
第二个值prototype,表示是多实例对象

演示多实例:

<bean id="book" class="com.atguigu.spring5.collectiontype.Book" scope="prototype">
        <property name="list" ref="bookList"></property>
    </bean>

在这里插入图片描述
(3)singleton和prototype区别

第一singleton单实例,prototype多实例
第二设置scope值是singleton时候,加载spring配置文件时候就会创建单实例对象
设置scope值是prototype时候,不是在加载spring配置文件时候创建对象,在调用getBean方法时候创建多实例对象
scope 里面可以放request 和session

八、IOC操作Bean管理(bean生命周期)

(一)生命周期

(1)从对象创建到对象销毁的过程

(二)bean生命周期

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

(三)演示bean生命周期

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("第五步,执行销毁的方法");
    }
}

<?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.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
        <property name="oname" value="shouji"></property>
    </bean>
</beans>
    @Test
    public void testbeam3() {
//        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();
    }

在这里插入图片描述

(四)bean的后置处理器,bean生命周期有七步

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

(五)演示添加后置处理器效果

(1)创建类,实现接口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;
    }
}
<!--    配置后置处理器-->
    <bean id="myBeanPost" class="com.atguigu.spring5.bean.MyBeanPost"></bean>
</beans>

在这里插入图片描述

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

(一)什么是自动装配

(1)根据指定装配规则(属性名称或者属性类型),Spring自动将匹配的属性值进行注入

(二)演示自动装配过程

(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.autowrie.Emp" autowire="byName">
<!--        <property name="dept" ref="dept"></property>-->
    </bean>
    <bean id="dept" class="com.atguigu.spring5.autowrie.Dept"></bean>
 </beans>

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

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

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

(一)直接配置数据库信息

(1)配置德鲁伊连接池
(2)引入德鲁伊连接池依赖jar包
在这里插入图片描述

<!--直接配置连接池-->
    <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="hsp"></property>
    </bean>

(二)引入外部属性文件配置数据库连接池

(1)创建外部属性文件,properties格式文件,写数据库信息
在这里插入图片描述
(2)把外部properties属性文件引入到spring配置文件中
*引入context名称空间

<?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">

在这里插入图片描述
⚫在spring配置文件使用标签引入外部属性文件

<!--引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--配置连接池-->
    <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>

十一、IOC操作Bean管理(基于注解方式)

(一)什么是注解

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

(二)Spring针对Bean管理中创建对象提供注解

(1)@Component 普通注解
(2)@Service 业务逻辑层 Service层
(3)@Controller 外部层
(4)@Repository DAO层和Mapper层
*上面四个注解功能是一样的,都可以用来创建bean实例

(三)基于注解方式实现对象创建

第一步引入依赖
在这里插入图片描述

第二步开启组件扫描

<!--开启组件扫描
        方式一 如果扫描多个包,多个包使用逗号隔开       <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>
    -->
    <context:component-scan base-package="com.atguigu.spring5"></context:component-scan>

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

package com.atguigu.spring5.service;

import org.springframework.stereotype.Component;

// 在注解里面value属性值可以省略不写,
// 默认值是类名称,首字母小写
// UserService -> userService
@Component(value = “userService”) //
public class UserService {
public void add() {
System.out.println(“service 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 testService() {
         ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(userService);
        userService.add();

    }

}

在这里插入图片描述

(四)开启组件扫描细节配置

<!--开启组件扫描
        方式一 如果扫描多个包,多个包使用逗号隔开       <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>
    -->
    <context:component-scan base-package="com.atguigu"></context:component-scan>

    <!--实例1
    use-default-filters="false"  表示现在不使用默认filter,自己配置filter
    context:include-filter,设置扫描哪些内容
        -->
<!--不扫描所有内容,只扫描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,设置不扫描哪些内容
        -->
    <context:component-scan base-package="com.atguigu" use-default-filters="false">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

(五)基于注解方式实现属性注入

(1)@Autowired:根据属性类型进行自动装配
第一步 把service和dao对象创建,在service和dao类添加创建对象注解
第二步 在service注入dao对象,在service类添加dao类型属性,在属性上面使用注解

@Service
public class UserService {
    // 定义dao类型属性
    // 不需要添加set方法
    // 添加注入属性注解
   @Autowired// 根据类型进行注入
    private UserDao userDao;
    public void add() {
        System.out.println("service add");
        userDao.add();
    }
}

(2)@Qualifier:根据属性名称进行注入
这个@Qualifier 注解的使用,和上面@Autowired一起使用

@Service
public class UserService {
    // 定义dao类型属性
    // 不需要添加set方法
    // 添加注入属性注解
   @Autowired // 根据类型进行注入
   @Qualifier(value = "userDaoImpl1") // 根据名称进行注入
    private UserDao userDao;
    public void add() {
        System.out.println("service add");
        userDao.add();
    }

}
@Repository(value = "userDaoImpl1")
public class UserDaoImpl implements UserDao{

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

(3)@Resource:可以根据类型注入,可以了根据名称注入

//    @Resource // 根据类型注入
    @Resource(name = "userDaoImpl1") // 根据名称进行注入
    private UserDao userDao;

(4)@Value:注入普通类型属性

@Value(value = "abc")
    private String name;

十二、完全注解开发

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

创建配置类

@Configuration // 作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.atguigu"})
public class SpringConfig {

}

替代配置文件

在这里插入图片描述

(二)编写测试类

在这里插入图片描述

十三、AOP(概述)

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

(二)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能

(三)使用登录例子说明AOP

在这里插入图片描述

十四、AOP(底层原理)

1、AOP底层使用动态代理
(1)有两种情况动态代理
第一种有接口情况,使用JDK动态代理
⚫创建接口实现类代理对象,增强类的方法
在这里插入图片描述
第二种没有接口情况,使用CGLIB动态代理
⚫创建子类的代理对象,增强类的方法
在这里插入图片描述

十五、AOP(JDK动态代理)

(一)使用JDK动态代理,使用Proxy类里面的方法创建代理对象

在这里插入图片描述
(1)调用newProxyInstance方法

在这里插入图片描述
方法有三个参数:
第一参数,类加载器
第二参数,增强方法所在的类,这个类实现的接口,支持多个接口
第三参数,实现这个接口InvocationHandler,创建代理对象,写增强的部分

(二)编写JDK动态代理代码

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

public interface UserDao {

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

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

public class UserDaoImp1 implements UserDao {

    @Override
    public int add(int a, int b) {
        return a + b;
    }

    @Override
    public String update(String id) {
        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;
//            }
//        });

        UserDaoImp1 userDao = new UserDaoImp1();
        UserDao dao = (UserDao) Proxy.newProxyInstance(JDKProxy.class.getClassLoader(), interfaces, new UserDaoProxy(userDao));
        int result = dao.add(1, 2);
        System.out.println("result = " + result);
    }
}

// 创建代理对象代码
class UserDaoProxy implements InvocationHandler {

    // 1 把创建的是谁的代理对象,把谁传递过来
    // 有参构造传递
    private Object obj;
    public UserDaoProxy(Object obj) {
        this.obj = obj;
    }

    // 增强的逻辑
    @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(术语)

在这里插入图片描述

(一)连接点

在这里插入图片描述

(二)切入点

在这里插入图片描述

(三)通知(增强)

在这里插入图片描述

(四)切面

在这里插入图片描述

十七、AOP操作(准备工作)

(一)Spring框架一般都是基于AspectJ实现AOP操作

(1)什么是AspectJ
AspectJ不是Spring组成部分,独立AOP框架,一般把AspectJ和Spirng框架一起使用,进行AOP操作

(二)基于AspectJ实现AOP操作

(1)基于xml配置文件实现
(2)基于注解方式实现(使用)

(三)在项目工程里面引入AOP相关依赖

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

(四)切入点表达式

(1)切入点表达式作用:知道对哪个类里面的哪个方法进行增强
(2)语法结构:
execution([权限修饰符] [返回类型] [类全路径] 方法名称 )

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

十八、AOP操作(AspectJ注解)

(一)创建类,在类里面定义方法

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

(二)创建增强类(编写增强逻辑)

(1)在增强类里面,创建方法,让不同方法代表不同通知类型

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

(三)进行通知的配置

(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"
       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>

(2)使用注解创建User和UserProxy对象
在这里插入图片描述
[外链图片转存失败,源站可能有防盗在这里插入!链机制,

(3)在增强类上面添加注解@Aspect

在这里插入图片描述

(4)在spring配置文件中开启生成代理对象

在这里插入图片描述

(四)配置不同类型的通知

(1)在增强类的里面,在作为通知方法上面添加通知类型注解,使用切入点表达式配置

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

    // 前置通知
    // @Before注解表示作为前置通知
    @Before(value = "execution(* com.atguigu.spring5.aopanno.User.add(..))")
    public void before() {
        System.out.println("before...");
    }
}
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();

        System.out.println("环绕之后...");
    }

}

没异常:
在这里插入图片描述

有异常在这里插入图片描述

(五)相同的切入点抽取 (@Pointcut)

在这里插入图片描述

在这里插入图片描述

(六)有多个增强类多同一个方法进行增强,设置增强类优先级(@Order)

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

在这里插入图片描述

(七)完全使用注解开发

(1)创建配置类,不需要创建xml配置文件
在这里插入图片描述

十九、AOP操作(AspectJ配置文件)

(一)创建两个类,增强类和被增强类,创建方法

(二)在spring配置文件中创建两个类对象

在这里插入图片描述

(三)在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">
       <!--创建对象-->
    <bean id="book" class="com.atguigu.spring5.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.atguigu.spring5.aopxml.BookProxy"></bean>

<!--配置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>
    @Test
    public void testAopXml() {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }

在这里插入图片描述

二十、JdbcTemplate(概念和准备)

(一)什么是JdbcTemplate

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

(二)准备工作

(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"
       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="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="hsp" />
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    </bean>
</beans>

(3)配置JdbcTemplate对象,注入DataSource
在这里插入图片描述
(4)创建service类,创建dao类,在dao注入jdbcTemplate对象
*配置文件
在这里插入图片描述
*service
在这里插入图片描述

*dao
在这里插入图片描述

(三)JbdcTemplate操作数据库(添加)

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

在这里插入图片描述
2、编写service和dao
(1)在dao进行数据库添加操作
(2)调用JdbcTemplate对象里面update方法实现添加操作
在这里插入图片描述
⚫有两个参数
⚫第一个参数:sql语句
⚫第二个参数:可变参数,设置sql语句值

@Repository
public class BookDaoImp1 implements BookDao{

    // 注入JdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 添加的方法
    @Override
    public void add(Book book) {
        // 1 创建SQL语句
        String sql = "insert into t_book values(?, ?, ?)";
        // 调用方法实现
        Object[] args = {book.getUserId(), book.getUsername(), book.getUstatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println("update = " + update);
    }
}

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

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

1、修改

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

@Override
    public void delete(String id) {
        String sql = "delete from t_book where user_id=?";
        int update = jdbcTemplate.update(sql, id);
        System.out.println("update = " + update);
    }

3.修改

        // 添加
//        Book book = new Book();
//        book.setUserId("1");
//        book.setUsername("java");
//        book.setUstatus("a");
//        bookService.addBook(book);

        // 修改
        Book book = new Book();
        book.setUserId("1");
        book.setUsername("javaaaa");
        book.setUstatus("at");
        bookService.updateBook(book);
// 删除
        bookService.deleteBook("1");

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

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

有两个类型
第一个参数:SQL语句
第二个参数:返回类型Class

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

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

1、场景:查询图书详情
2、JdbcTemplate实现查询返回对象
在这里插入图片描述
⚫有三个参数
⚫第一个参数:sql语句
⚫第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
⚫第三个参数:sql语句值

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

(七)JdbcTemplate操作数据库(查询返回集合)

1、场景:查询图书列表分页…
2、调用JdbcTemplate方法实现查询返回集合
在这里插入图片描述
⚫有三个参数
⚫第一个参数:sql语句
⚫第二个参数:RowMapper是接口,针对返回不同类型数据,使用这个接口里面实现类完成数据封装
⚫第三个参数:sql语句值

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

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

1、批量操作:操作表里面多条记录
2、JdbcTemplate实现批量添加操作
在这里插入图片描述
⚫有两个参数
⚫第一个参数:sql语句
⚫第二个参数:List集合,添加多条记录数据

    // 批量添加
    @Override
    public void findAddAllBook(List<Object[]> batchArgs) {
        String sql = "insert into t_book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
// 批量添加
        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);

(九)3、JdbcTemplate实现批量修改操作

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

二十一、事务操作(事务概念)

(一)什么事务

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

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

(二)事务四个特性(ACID)

(1)原子性
(2)一致性
(3)隔离性
(4)持久性
事务操作(搭建事务操作环境)

在这里插入图片描述

1、创建数据库表,添加记录
2、创建service,搭建dao,完成对象创建和注入关系在这里插入图片描述
(1)service注入dao,在dao注入JdbcTemplate,在JdbcTemplate注入DataSource

@Service
public class UserService {
    // 注入dao
    @Autowired
    private UserDao userDao;
}
@Repository
public class UserDaoImpl implements UserDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
}

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

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

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

4、上面代码,如果正常执行没有问题的,但是如果代码执行过程中出现异常,有问题

在这里插入图片描述

(1)上面问题如何解决呢?
*使用事务进行解决
(2)事务操作过程

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


            // 第二步 进行事务操作


            // Lucy少100
            userDao.reduceMoney();

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

            // mary多100
            userDao.addMoney();

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

    }

二十二、事务操作(Spring事务管理介绍)

1、事务添加到JavaEE三层结构里面Service层(业务逻辑层)
2、在Spring进行事务管理操作
(1)有两种方式:编程式事务管理和声明式事务管理(使用)
3、声明式事务管理
(1)基于注解方式(使用)
(2)基于xml配置文件方式
4、在Spring进行声明式事务管理,底层使用AOP原理
5、Spring事务管理API
(1)提供一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类
在这里插入图片描述

二十三、事务操作(注解声明式事务管理)

(一)在spring配置文件配置事务管理器

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

(二)在spring配置文件,开启事务注解

(1)在spring配置文件引入名称空间tx

<?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-aop.xsd">

(2)开启书屋注解

<!--开启事务注解-->
    <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

(三)在service类上面(获取service类里面方法上面)添加事务注解

(1)@Transactional,这个注解添加到类上面,也可以添加方法上面
(2)如果把这个注解添加类上面,这个类里面所有的方法都添加事务
(3)如果把这个注解添加方法上面,为这个方法添加事务

@Service
@Transactional
public class UserService {

二十四、事务操作(声明式事务管理参数配置)

(一)在service类上面添加注解@Transactional,在这个注解里面可以配置事务相关参数

在这里插入图片描述

(二)propagation:事务传播行为

(1)多事务方法直接进行调用,这个过程中事务是如何进行管理的

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

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

(三)ioslation:事务隔离级别

(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读
(3)脏读:一个未提交事务读取到另一个未提交事务的数据

在这里插入图片描述
(4)不可重复读:一个未提交事务读取到另一提交事务修改数据
在这里插入图片描述
(5)虚读:一个未提交事务读取到另一提交事务添加数据
(6)解决:通过设置事务隔离级别,解决读问题

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

(四)timeout:超时时间

(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是-1,设置时间以秒单位进行计算

(五)readOnly:是否只读

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

(六)rollbackFor:回滚

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

(七)noRollbackFor:不回滚

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

二十五、事务操作(XML声明式事务管理)

(一)在spring配置文件中进行配置

第一步配置事务管理器第二步配置通知

第二步 配置通知

第三步 配置切入点和切面


<!--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: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>

二十六、事务操作(完全注解声明式事务管理)

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;
import javax.xml.crypto.Data;

@Configuration // 配置类
@ComponentScan(basePackages = "com.atguigu") // 开启文件扫描
@EnableTransactionManagement // 开启事务
public class TxConfig {

    // 创建数据库连接池
    @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("hsp");
        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;
    }
}

二十七、Spring5框架新功能

1、整个Spring5框架的代码基于Java8,运行时兼容JDK9,许多不建议使用的类和方法在代码库中删除
2、Spring 5.0框架自带了通用的日志封装
(1)Spring5已经移除Log4jConfigListener,官方建议使用Log4j2
(2)Spring5框架整合Log4j2
第一步引入jar包

在这里插入图片描述
第二步创建log4j2.xml配置文件

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值