Spring框架概述

1.Spring框架概述

(1)轻量级开源javaEE框架,为了解决企业复杂性,两个核心组成:IOC和AOP

(2)Spring5.2.6版本

2.IOC容器

(1)IOC底层原理

(2)IOC接口(BeanFactory)

(3)IOC操作Bean管理(基于xml)

(3)IOC操作Bean管理(基于注解)

(3)IOC操作Bean管理(完全注解)

3.AOP

(1)AOP底层原理:动态代理,有接口(jdk动态代理),没有接口(CGLIB动态代理)

(2)术语:连接点 切入点 增强(通知) 切面

4.JdbcTemplate

(1)使用JdbcTemplate实现数据库的增删改查操作

(2)使用JdbcTemplate实现数据库批量操作

5.事务管理

(1)事务概念

(2)重要概念(擦传播行为和隔离级别)

(3)基于注解实现

6.Spring5新特性

(1)整合日志框架

(2)@Nullable注解

(3)函数式注册对象

(4)整合JUnit5单元测试框架

(5)SpringWebflux

一.Spring是轻量级的java开发框架或开发容器

为什么说是一种开发容器

Spring里的所有bean都回被封装成BeanDefinition对象,然后通过BeanDefinitionRegistry接口注册到一个Map中,这个Map的key就是你xml配置文件里写的<bean> 标签的id属性或者是你在@Configuration注解标签的配置类里@Bean的name属性的值,value就是封装好的BeanDefinition,所以Spring就是对Map进行了一个高度封装,由于Map是容器,所以Spring也是一种容器

1.1轻量级:相较于重量级的EJB

1.2Spring是非侵入式的:典型地,Spring应用中的对象不依赖于Spring的特定类

2.目的:为了解决企业级应用开发的复杂性,简化java开发

3.框架核心:IOC和AOP

        3.1.IOC(控制反转)

        3.2.AOP(面向切面编程)

4.Spring特点:

(1)方便解耦,简化开发

        Spring 就是一个大工厂,可以将所有对象的创建和依赖关系的维护交给 Spring 管理。

(2)AOP编程支持

        Spring 提供面向切面编程,可以方便地实现对程序进行权限拦截和运行监控等功能。

(3)方便程序测试

        Spring 支持 JUnit4,可以通过注解方便地测试 Spring 程序。

(4)方便和其他框架进行整合

        Spring 不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(如 Struts2、Hibernate、MyBatis 等)的直接支持

(5)方便进行事务的操作

         只需要通过配置就可以完成对事务的管理,而无须手动编程

(6)降低API应用难度

        Spring 对 Java EE 开发中非常难用的一些 API(JDBC、JavaMail、远程调用等)都提供了封装,使这些 API 应用的难度大大降低。

(7)java源代码的学习典范

二、IOC容器

①IOC底层原理

②IOC接口(BeanFactory)

③IOC操作Bean管理(基于xml)

④IOC操作Bean管理(基于注解)

什么是IOC:

(1)控制反转:平常比如我们运行A类的时候需要用到B类这时A运行到需要B类的时候就会自主的创建B类或调用B类 创建对象或者调用对象的权力在A类的手中。当我们使用控制反转之后就把创建B或调用B对象的权力转交给IOC容器去执行,由主动创建变为被动创建。从而降低耦合度。

IOC的底层原理:

(1)xml解析、工厂模式、反射

没有IOC的时候UserServer与具体的实现类User耦合当如果你需要多个实现类的时候耦合度就会比较高  但是有了IOC后UserService只与UserFactory工厂类耦合即使有多个实现类UserService也只和UserFactory耦合从而降低了耦合度。

  xml:只需要通过配置文件就能创建对象 减少与实现类之间的耦合

使用Service类和Dao接口实现类:使用的时候原本需要与多个实现类耦合 但是现在 只需调用接口就可以

IOC(接口)

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

2.Spring提供IOC容器实现两种方式:(两个接口)

(1)BeanFactory

(2) ApplicationContext

       //实现IOC的两个接口   BeanFactory的子接口,提供更多更强大的功能 提供给开发人员使用
        //加载配置文件的时候就已经创建对象  把耗时的操作在服务器启动的时候交给服务器去完成 也就是我们选择用ApplicationContext的原因
        //1.1ApplicationContext接口一
//        ApplicationContext context=
//                new ClassPathXmlApplicationContext("bean1.xml");

        ApplicationContext context=
                new FileSystemXmlApplicationContext("C:\\Users\\86130\\IdeaProjects\\SpringDemo\\src\\bean1.xml");//全盘路径

        //1.2BeanFactory接口二  IOC容器的基本实现 是Spring内部的使用接口,不提供开发人员使用
        //加载配置文件的时候不会去创建对象 获取对象使用的时候才回去创建对象
//        BeanFactory context=
//                new ClassPathXmlApplicationContext("bean1.xml");

3.IOC操作Bean管理

3.1什么是Bean管理

Bean管理指的是两个操作

        ①Spring创建对象

        ②Spring注入属性

Bean管理操作有两种方式

        ①基于xml配置文件方式实现

        ②基于注解方式实现

IOC操作Bean管理(基于xml)

1.基于xml方式创建对象

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

①在Spring配置文件中,使用bean标签,标签里面添加对应属性,就可以实现对象创建

②在bean标签中有很多属性,介绍常用的属性:

        id属性:唯一标识

        class属性:类全路径(包类路径)

③创建属性的时候,默认也是执行无参构造方法完成对象创建

2.基于xml方式注入属性

①DI:依赖注入,就是注入属性

        第一种注入方式:使用set方法进行注入

        (1)创建类,定义属性和对应的set方法

public class Book {
    //创建属性
    private String bookName;
    private String bookAuthor;
    //创建属性对应的set方法
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public void setBookAuthor(String bookAuthor) {
        this.bookAuthor = bookAuthor;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookName='" + bookName + '\'' +
                ", bookAuthor='" + bookAuthor + '\'' +
                '}';
    }


//以下是我们原始的方法 可以忽略
    public static void main(String[] args) {
        Book book=new Book();
        book.setBookName("降龙十八掌");
        book.setBookAuthor("洪七公");
        System.out.println(book.bookName+":"+book.bookAuthor);
    }
}

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

 <bean id="book" class="com.atubo.spring.Book">
<!-- 使用property完成属性注入  name:类里面属性名称 value:向属性注入的值-->
        <property name="bookName" value="降龙十八掌"></property>
        <property name="bookAuthor" value="洪七公"></property>
    </bean>

        (3)在测试类里面调用:

    @Test
    public void test1(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");
        Book book=context.getBean("book",Book.class);
        System.out.println(book);
    }

        第二种注入方式:使用有参数构造进行注入

        (1)定义类的属性和带参构造器

public class Order {
    private String orderName;
    private String OrderAddress;

    public Order(String orderName, String orderAddress) {
        this.orderName = orderName;
        OrderAddress = orderAddress;
    }

    @Override
    public String toString() {
        return "Order{" +
                "orderName='" + orderName + '\'' +
                ", OrderAddress='" + OrderAddress + '\'' +
                '}';
    }
}

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

<bean id="order" class="com.atubo.spring.Order">
        <constructor-arg name="orderName" value="手机"></constructor-arg>
        <constructor-arg name="orderAddress" value="China"></constructor-arg>
    </bean>

p名称空间注入(了解)

使用p名称空间注入,可以简化基于xml配置方式

        第一步添加p名称空间在配置文件

<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标签里面进行操作

<!--    p名称空间简化-->
    <bean id="book" class="com.atubo.spring.Book" p:bookName="降龙十八掌" p:bookAuthor="洪七公"></bean>

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

1.字面量

  (1)null值

<!--        添加null值-->
        <property name="bookAddress">
            <null></null>
        </property>

  (2)属性包含特殊符号

           1.把<>进行转义&lt;&gt

           2.把带特殊符号内容写到CDATA

        <property name="bookAddress">
            <value><![CDATA[<<南京>>]]></value>
        </property>

2.注入属性---外部bean

(1)创建两个类server类和DAO接口的实现类

        Dao接口:

public interface UserDao {
    public abstract void update();
}

        Dao接口实现类:

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

        server类:

public class UserService {
    //通过定义属性 set方法获取属性
    private UserDao userDao;

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

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

        //原始方式
        //创建UserDao对象
//        UserDao userDao=new UserDaoImpl();
//        userDao.update();
    }
}

(2)在server调用DAO里面的方法

public class UserService {
    //通过定义属性 set方法获取属性
    private UserDao userDao;

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

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

        //原始方式
        //创建UserDao对象
//        UserDao userDao=new UserDaoImpl();
//        userDao.update();
    }
}

(3)在Spring配置文件中进行配置

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

3.注入属性---内部bean和级联赋值

(1)一对多关系:部门员工

        一个部门有多个员工,一个员工属于一个部门

        部门是一,员工是多

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

部门类:

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


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

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

员工类:

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

    public Department getDept() {
        return dept;
    }

    public void setDept(Department dept) {
        this.dept = dept;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "ename='" + ename + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }
}

(3)在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">
<!--内部Bean-->
    <bean id="employee" class="com.atubo.spring.bean.Employee">
        <property name="ename" value="霸王龙"></property>
        <property name="gender" value="男"></property>
        <property name="dept">
            <bean id="department" class="com.atubo.spring.bean.Department">
                <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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<!--    级联赋值-->
    <bean id="employee" class="com.atubo.spring.bean.Employee">
        <property name="ename" value="霸王龙"></property>
        <property name="gender" value="男"></property>
<!--        级联赋值1-->
        <property name="dept" ref="department"></property>
<!--        级联赋值二   这种写法需要提供get方法-->
        <property name="dept.dname" value="技术部"></property>
    </bean>
    <bean id="department" class="com.atubo.spring.bean.Department">
        <property name="dname" value="不懂事部"></property>
    </bean>

</beans>

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

1.注入数组类型属性

2.注入List类型属性

3.注入Map类型属性

4.注入set类型属性

步骤一:创建类,定义数组、list、map、set类型属性,生成对应的set方法

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

public class Student {
    //1.数组类型的属性
    private String[] name;
    //2.list类型的属性
    private List<String> number;
    //3.map类型的属性
    private Map<Integer,String> courses;
    //4.set类型的属性
    private Set<String> teacher;

    public void setName(String[] name) {
        this.name = name;
    }

    public void setNumber(List<String> number) {
        this.number = number;
    }

    public void setCourses(Map<Integer, String> courses) {
        this.courses = courses;
    }

    public void setTeacher(Set<String> teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name=" + Arrays.toString(name) +
                ", number=" + number +
                ", courses=" + courses +
                ", teacher=" + teacher +
                '}';
    }
}

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

<!--    集合类型的属性注入-->
    <bean id="student" class="com.atubo.spring.collectionType.Student">
        <property name="name">
            <array>
                <value>小白鼠</value>
                <value>霸王龙</value>
                <value>独角兽</value>
            </array>
        </property>
        <property name="number">
            <list>
                <value>201912904513</value>
                <value>201912904580</value>
                <value>201912904515</value>
            </list>
        </property>
        <property name="courses">
            <map>
                <entry key="102" value="数据库"></entry>
                <entry key="105" value="java"></entry>
                <entry key="109" value="Spring"></entry>
            </map>
        </property>
        <property name="teacher">
            <set>
                <value>陈东东</value>
                <value>王西西</value>
                <value>何南南</value>

            </set>
        </property>
    </bean>
</beans>

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

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

            </list>
        </property>
    </bean>
<!--    创建多个bean-->
    <bean id="course1" class="com.atubo.spring.collectionType.Course">
        <property name="cname" value="操作系统"></property>
    </bean>
    <bean id="course2" class="com.atubo.spring.collectionType.Course">
        <property name="cname" value="SpringBoot"></property>
    </bean>
    <bean id="course3" class="com.atubo.spring.collectionType.Course">
        <property name="cname" value="计算机网络"></property>
    </bean>

把集合注入部分提取出来

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-util.xsd">


<!--    提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>降龙十八掌</value>
        <value>乾坤大挪移</value>
        <value>天外飞仙</value>
    </util:list>
<!--    提取list集合类型属性注入使用-->
    <bean id="book" class="com.atubo.spring.collectionType.BookName">
        <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类型

MyBean:

import com.atubo.spring.collectionType.Course;
import org.springframework.beans.factory.FactoryBean;

public class MyBean implements FactoryBean<Course> {
    //返回的实例
    @Override
    public Course getObject() throws Exception {
        Course course=new Course();
        course.setCname("cht");
        return course;
    }

    @Override
    public Class<?> getObjectType() {
        return null;
    }
    //返回值类型是否是单例
    @Override
    public boolean isSingleton() {
        return FactoryBean.super.isSingleton();
    }
}

course:

//课程类
public class Course {
    private String cname;

    public void setCname(String cname) {
        this.cname = cname;
    }

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

配置文件:

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

    <bean id="myBean" class="com.atubo.spring.factoryBean.MyBean">

    </bean>
</beans>

IOC操作Bean的管理(bean作用域)

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

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

    <bean id="book" class="com.atubo.spring.collectionType.BookName">
        <property name="list" ref="bookList"></property>
    </bean>
@Test
    public void testCollectionType1(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean6.xml");
        BookName bookList1=context.getBean("book",BookName.class);
        BookName bookList2=context.getBean("book",BookName.class);

        System.out.println(bookList1);
        System.out.println(bookList2);
    }

结果:

3.如何设置单实例还是多实例

(1)在Spring配置文件bean标签里面有属性(scope)用于设置单实例还是多实例

(2)scope属性值

        第一个值 默认值,singleton,表示是单实例对象

        第二个值 prototype,表示是多实例对象

        对配置文件的scope进行修改:

   <bean id="book" class="com.atubo.spring.collectionType.BookName" scope="prototype">
        <property name="list" ref="bookList"></property>
    </bean>

结果值:

 3.singleton和prototype区别

第一 singleton单实例,prototype多实例

第二 设置scope值是singleton的时候,加载Spring配置文件的时候就会创建单实例对象

        设置scope值是prototype的时候,不是在加载Spring配置文件时候创建对象,在调用getBean方法的时候创建多实例对象

request:表示一次请求

session:一次会话

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

1.生命周期

        从对象创建到对象销毁的过程

2.bean生命周期

(1)通过构造器创建bean实例(无参数构造)

(2)为bean的属性设置值和对其他bean引用(调用set方法)

(3)调用bean的初始化的方法(需要进行配置初始化的方法)

        补充(什么是初始化)如果不是初始化的方法我们需要手动调用的时候才能知道值得变化 如果是初始化方法在一开始的时候就会先去执行一遍  静态方法就是初始化方法

(4)bean可以使用了(对象获取到)

(5)当容器关闭的时候,调用bean的销毁方法(需要进行配置销毁的方法)

3.bean生命周期的演示

Fruit类:

public class Fruit {
    private String fname;

    public Fruit() {
        System.out.println("第一步: 调用无参构造函数");
    }

    public void setFname(String fname) {
        System.out.println("第二步 调用set方法设置属性值");
        this.fname = fname;
    }
    //创建执行初始化方法
    public void initMethod(){
        System.out.println("第三步:执行初始化方法");
    }

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

}

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

    <bean id="fruit" class="com.atubo.spring.BeanLifeCycle.Fruit" init-method="initMethod" destroy-method="destroyMethod">
        <property name="fname" value="榴莲"></property>
    </bean>
</beans>

Test类:

    @Test
    public void testBeanLifeCycle(){
        ClassPathXmlApplicationContext context=
                new ClassPathXmlApplicationContext("bean8.xml");
        Fruit fruit = context.getBean("fruit", Fruit.class);
        System.out.println("第四步:获取到bean对象");
        System.out.println(fruit);

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

运行结果:

 4.bean的后置处理器,bean生命周期有七步

(1)通过构造器创建bean实例(无参数构造)

(2)为bean的属性设置值和对其他bean引用(调用set方法)

(3)把bean实例传递bean后置处理器的方法 postProcessBeforeInitialization

(4)调用bean的初始化的方法(需要进行配置初始化的方法)

(5)把bean实例传递bean后置处理器的方法 postProcessAfterInitialization

(6)bean可以使用了(对象获取到)

(7)当容器关闭的时候,调用bean的销毁方法(需要进行配置销毁的方法)

5.演示添加后置处理器的效果

(1)创建类,接口实现BeanPostProcessor 创建后置处理器 

//bean的后置处理器
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;
    }
}

2.让Spring知道它是后置处理器

<!--    后置处理器  一旦后置处理器定义之后 xml文件中的每个bean都会默认使用后置处理器-->
<!--    Spring是如何知道它是后置处理器的呢?&ndash;&gt;因为该类继承了BeanPostProcessor接口-->
    <bean id="myBeanPost" class="com.atubo.spring.BeanLifeCycle.MyBeanPost"></bean>

运行结果:

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

1.什么是自动装配

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

2.演示自动装配的过程

1.byName根据属性名称注入,注入值bean的id值和类属性名称一样


    <bean id="dept" class="com.atubo.spring.autowire.Dept">
        <property name="dname" value="数据库"></property>
    </bean>
           byName根据属性名称注入,注入值bean的id值和类属性名称一样
    <bean id="emp" class="com.atubo.spring.autowire.Emp" autowire="byName">

    </bean>

2.byType根据属性类型注入,注入的值根据类型来匹配 当出先同个类型存在多个bean的时候只能选择byName


    <bean id="dept" class="com.atubo.spring.autowire.Dept">
        <property name="dname" value="数据库"></property>
    </bean>
<!--           byName根据属性名称注入,注入值bean的id值和类属性名称一样-->
<!--    <bean id="emp" class="com.atubo.spring.autowire.Emp" autowire="byName">-->

<!--    </bean>-->
    <bean id="emp" class="com.atubo.spring.autowire.Emp" autowire="byType">

    </bean>

IOC操作bean管理(引用外部文件)

  (1)创建外部属性文件,properties格式文件,写数据库信息

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

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

        引入context名称空间

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

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

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

<!--    配置连接池-->
        <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.什么是注解

(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值,属性名称=属性值)

(2)使用注解,注解使用在类上,方法上面,属性上面

(3)使用注解目的:简化xml配置

2.Spring针对Bean管理中创建对象提供注解

        ①@Component

        ②@Service

        ③@Controller

        ④@Repository

        四个注解都可以用来创建Bean对象

3.基于注解方式实现对象创建

第一步 引入依赖

第二步开启组件扫描

<?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: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.atubo"></context:component-scan>

</beans>

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

/*
在注解里面value属性值可以省略不写就是将(value="userService")去掉
去掉后是为类名称在将首字母变成小写
UserService-->userService

 */
@Component(value = "userService")  //相当于之前xml文件中的<bean id="userService" class="">
public class UserService {
    public void add(){
        System.out.println("service add.....");
    }
}

 测试类中测试的代码和结果如下:

    @Test
    public void testUserService(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");
        UserService service = context.getBean("userService", UserService.class);
        System.out.println(service);
        service.add();

    }

 4.开启组件扫描的一些配置细节

<!--示例一
        只扫描Component类型的注解-->
    <context:component-scan base-package="com.atubo.spring" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>
<!--    示例二
        只有Component类型的注解不扫描-->
    <context:component-scan base-package="com.atubo.spring">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>

5.基于注解方式实现属性注入

①@AutoWired:根据属性类型进行自动装配

第一步 把service和dao对象创建,在service和dao类添加创建对象注解

第二步 在service注入dao对象,在service类中添加dao类型属性,在属性上面使用注解

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

③@Resource:可以根据类型注入,也可以根据名称注入

//    @Resource//根据类型进行注入
    @Resource(name = "userDaoImpl")//根据名称进行注入
    private UserDao userDao;
    public void add(){
        System.out.println("service add.....");
        userDao.add();
    }

④@Value:注入普通类型属性

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

IOC操作Bean管理(完全注解)

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

@Configuration//作为配置类,替代xml配置文件
@ComponentScan(basePackages = {"com.atubo.spring"})//替代xml中的扫描代码

(2)编写测试类

    @Test
    public void testUserService1(){
        ApplicationContext context=
                new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService service = context.getBean("userService", UserService.class);
        System.out.println(service);
        service.add();

    }

AOP

1.什么是AOP

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

不通过修改源代码的方法添加新方法

如图:

AOP的底层原理

1.AOP底层使用动态代理

        (1)有了两种情况的动态代理

        第一种 有接口的情况 使用jdk动态代理

        jdk动态代理的源码

package reflection;

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

/**动态代理的举例
 * 要有接口 被代理类  代理类是动态的
 * @Author:阿土伯
 * @Date: 2022/2/16 16:45
 */
interface Human{
    String getBelief();
    void eat(String food);
}
//被代理类
class SuperMan implements Human{

    @Override
    public String getBelief() {
        return "I believe I can fly!";
    }

    @Override
    public void eat(String food) {
        System.out.println("我喜欢吃食物"+food);
    }
}
//动态代理和面向切面编程AOP的结合
class HumanUtil{
    public void method1(){
        System.out.println("==========通用方法一=============");
    }
    public void method2(){
        System.out.println("=========通用方法二==============");
    }
}
/*
要想实现动态代理,需要解决的问题?
问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象
问题二:当通过代理类的对象调用方法时,如何动态的去调用被代理类中的同名方法。
 */

class ProxyFactory{
    //调用此方法,返回一个代理类对象。解决问题一
    //此时返回类型是Object而不是Human的原因是因为我们代理类不只要代理Human还要代理其他类 如果写Human就写死了
    public static Object getProxyInstance(Object obj){//obj:被代理类的对象
        //实例化MyInvocationHandler
        MyInvocationHandler handler=new MyInvocationHandler();
        //此时调用该方法的目的是为了将目标对象引进去
        handler.bind(obj);
        //调用该方法创建代理类对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);//调用该方法时就会去调用MyInvocationHandler中的invoke方法

    }
}
class MyInvocationHandler implements InvocationHandler{

    private Object obj;//需要使用被代理类的对象进行赋值
    public void bind(Object obj){
        this.obj=obj;
    }
    //当我们通过调用代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
    //将被代理类要执行的方法a的功能就声明在invoke中
    //此时的proxy就是代理类返回的对象roxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
    // method方法就是上面代理类调用的方法roxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);这个调用什么方法这时也就会调用什么方法

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        HumanUtil util=new HumanUtil();
        util.method1();
        //method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
        //obj:被代理类的对象 调用被代理类中的同名方法  解决了问题二
        Object returnValue = method.invoke(obj, args);

        util.method2();
        //上述方法的返回值也就作为当前类中invoke()的返回值
        return returnValue;
    }
}
public class ProxyTest {
    public static void main(String[] args) {
        //实例化被带了类的对象  引入目标
        SuperMan superMan=new SuperMan();
        //proxyInstance:代理类的对象  通过反射获取代理类对象
        Human proxyInstance=(Human) ProxyFactory.getProxyInstance(superMan);
        //当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法
        String belief=proxyInstance.getBelief();
        System.out.println(belief);
        proxyInstance.eat("海蛎煎");
        //此时做到通过调用代理类的方法从而调用被代理的方法而且还屏蔽了被代理类  体现了代理
        System.out.println("**************************************");


        //第二个例子:
        //实例化被代理类  引入目标对象
        NickClothFactory nickClothFactory = new NickClothFactory();
        //通过反射动态获得代理类对象
        ClothFactory proxyClothFactory=(ClothFactory) ProxyFactory.getProxyInstance(nickClothFactory);
        //调用代理类的方法从而实现调用被代理类的方法
        proxyClothFactory.produceCloth();
    }
}

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

AOP(术语)

1.连接点

        类里面哪些方法可以被增强,这些方法称为连接点

2.切入点

        实际被真正增强的方法,称为切入点

3.通知(增强)

(1)实际增强的逻辑部分称为通知(增强)

(2)通知有多种类型

        前置通知

        后置通知

        环绕通知

        异常通知

        最终通知 finaly

4.切面

         是一种动作

(1)把通知应用到切入点的过程

        比如前面说的将权限判断的功能加入到登录的过程就叫做切面

AOP的准备工作

1.Spring框架中一搬基于ASpectj实现AOP操作

(1)什么是Aspectj

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

2.基于AspectJ实现AOP操作

(1)基于xml配置文件实现

(2)基于注解方式实现(使用)

3.在项目中里面引入AOP相关依赖

 4.切入点表达式

(1)切入点表达式的作用:知道对哪个类里面的哪个方法进行增强

(2)语法结构

execution([权限修饰符][返回值类型][类的全路径][方法名称][参数列表])

举例一:对com.atubo.spring.dao.BookDao类里面的add进行增强

execution(* com.atubo.spring.dao.BookDao.add(..))

举例二:对com.atubo.spring.dao.BookDao类里面的所有方法进行增强

execution(* com.atubo.spring.dao.BookDao.*(..))

举例三:对com.atubo.spring.dao包下面所有类的所有方法进行增强

execution(* com.atubo.spring.dao.*.*(..))

AOP(AspectJ注解)

1.创建类,在类里面定义

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

2.创建增强类(编写增强逻辑)

public class UserProxy {

    //前置通知
    public void before(){
        System.out.println("before....");
    }
}

3.进行通知配置

(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.atubo.spring.aop"></context:component-scan>
</beans>

(2)使用注解创建User和UserProxy对象

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

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

<!--    开启Aspect生成代理对象   添加这行代码后自动去扫描文件中是否含有@Aspect的注解 如果有的话将生成代理类对象-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>

4.配置不同类型的通知

(1)在增强类的里面配置不同类型的通知

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

    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void before(){
        System.out.println("before....");
    }

    //方法返回之后执行  最终通知 相当于finaly
    @After(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void after(){
        System.out.println("after....");
    }

    //AfterReturning在方法返回结果之后执行  一旦有异常就不执行
    @AfterReturning(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void afterReturning(){
        System.out.println("afterReturning....");
    }

    //异常通知
    @AfterThrowing(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void afterThrowing(){
        System.out.println("afterThrowing....");
    }

    //环绕通知
    @Around(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前");
        //执行被增强的方法
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后");
    }
}

5.相同(公共)切入点进行提取

    //相同切入点的抽取
    @Pointcut(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void pointDemo(){

    }

    //前置通知
    //@Before注解表示作为前置通知
    @Before(value = "pointDemo()")
    public void before(){
        System.out.println("before....");
    }

6.有多个增强类对同一个方法进行增强,设置增强类的优先级

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

@Component
@Aspect
@Order(1)
public class PersonProxy {
    @Before(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void before(){
        System.out.println("Person before....");
    }
}
//增强类
@Component
@Aspect  //生成代理对象
@Order(2)
public class UserProxy {
    //相同切入点的抽取
    @Pointcut(value = "execution(* com.atubo.spring.aop.User.add(..))")
    public void pointDemo(){

    }

7.完全使用注解开发

//完全使用注解
@Configuration
@ComponentScan(basePackages = {"com.atubo.spring.aopConfig"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

AOP操作(Aspect配置文件)

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

public class Book {
    public void book(){
        System.out.println("book.......");
    }
}
public class BookProxy {
    public void before(){
        System.out.println("before.....");
    }
}

2.在spring中配置文件创建两个类对象

    <bean id="book" class="com.atubo.spring.aopxml.Book"></bean>
    <bean id="bookProxy" class="com.atubo.spring.aopxml.BookProxy"></bean>

3.在spring配置文件中配置切入点

 <aop:config>
<!--        切入点-->
        <aop:pointcut id="point" expression="execution(* com.atubo.spring.aopxml.Book.book(..))"/>
<!--        配置切面-->
        <aop:aspect ref="bookProxy">
<!--            增强作用在具体方法上面-->
            <aop:before method="before" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

三 JdbcTemplate(概念和准备)

1.什么是JdbcTemplate

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

准备工作

1.新引进的依赖: 

(2)在spring配置数据库连接池

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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">

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

(3)配置JdbcTemplate对象,注入DataSource

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

    <!--    引入外部属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--    配置连接池-->
    <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>
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--        注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

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

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

1.数据库实体类的创建

public class User {
    private String userId;
    private String userName;
    private String userStatus;

    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 getUserStatus() {
        return userStatus;
    }

    public void setUserStatus(String userStatus) {
        this.userStatus = userStatus;
    }
}

2.编写service和dao

(1)在dao中进行数据库添加操作

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

    //添加方法
    @Override
    public void add(Book book) {
        //1.创建sql语句
        String sql="insert into book value(?,?,?)";
//        //2.调用方法实现
//        int update = jdbcTemplate.update(sql, book.getUserId(), book.getUserName(), book.getUserStatus());
        //也可以这样写
        Object[] args={book.getUserId(),book.getUserName(),book.getUserStatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }
}

(2)调用JdbcTemplate对象里面update方法实现操作

        有两个参数

        第一个参数:sql语句

        第二个参数:可变参数,设置sql语句值

@Override
    public void add(Book book) {
        //1.创建sql语句
        String sql="insert into book value(?,?,?)";
//        //2.调用方法实现
//        int update = jdbcTemplate.update(sql, book.getUserId(), book.getUserName(), book.getUserStatus());
        //也可以这样写
        Object[] args={book.getUserId(),book.getUserName(),book.getUserStatus()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

测试:
 

    @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("spring");
        book.setUserStatus("a");
        bookService.addBook(book);
    }

结果:

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

    @Override
    public void remove(String id) {
        //1.创建sql语句
        String sql="delete from book where id=?";
        //调用方法实现
        int update = jdbcTemplate.update(sql, id);
        System.out.println(update);
    }

    //修改
    @Override
    public void alter(Book book) {
        //创建sql语句
        String sql="update book set name=?,status=? where id=?";
        //调用对象方法
        Object[] args={book.getUserName(),book.getUserStatus(),book.getUserId()};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

 测试类:

    @Test
    public void testJdbcTemplate(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book=new Book();
        book.setUserId("2");
        book.setUserName("springMVC");
        book.setUserStatus("c");
        //添加
//        bookService.addBook(book);
        //修改
//        bookService.alterBook(book);
        //删除
        bookService.removeBook(book.getUserId());
    }

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

查询表里面有多少条记录,返回某个值

1.使用jdbcTemplate实现查询返回某个值代码

 有两个参数

一个是sql语句

第二个:返回类型的class

    @Override
    public int selectCount() {
        //sql语句
        String sql="select count(*) from book";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        System.out.println(count);
        return count;

    }

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

1.场景:查询图书详情 需要返回对象

2.JdbcTemplate实现查询返回对象

方法中有三个参数 

第一个:sql语句

第二个:RowMapper,本事是一个接口,返回不同类型数据,使用这个接口里面实现类完成数据封装

第三个:sql语句值

    @Override
    public Book findBookInfo(String id) {
        //创建sql语句   此时需要注意实体类的属性 也就是Book的属性要和数据库中的字段名一样  否则查找出来都是空
        String sql="select * from book where userId=?";
        //调用方法
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }

测试类:

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

结果:

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

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

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

有三个参数:
第一个:sql语句

第二个:RowMapper,本事是一个接口,返回不同类型数据,使用这个接口里面实现类完成数据封装


    @Override
    public List<Book> findALlBook() {
        //创建sql语句
        String sql="select * from book";
        List<Book> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return list;

    }

测试类:

        //查询返回集合
        List<Book> all = bookService.findAll();
        Iterator<Book> iterator = all.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }

结果:

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

1.批量操作:操作表里面多条记录

2.JdbcTemplate实现批量添加操作

    //实现的底层原理 将list中的object[]数组一个个提取出来执行insert into book value(?,?,?)
    @Override
    public void batchAllBook(List<Object[]> bookList) {
        //创建sql语句
        String sql="insert into book value(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, bookList);
        System.out.println(Arrays.toString(ints));

    }

批量添加测试

        //批量添加
        List<Object[]> bookList=new ArrayList<>();
        Object[] o1={"4","mysql","d"};
        Object[] o2={"5","python","e"};
        Object[] o3={"6","c++","f"};
        bookList.add(o1);
        bookList.add(o2);
        bookList.add(o3);
        bookService.batchAdd(bookList);

结果:

 3.JdbcTemplate实现批量修改操作

    @Override
    public void batchUpdateBook(List<Object[]> bookList) {
        //创建sql语句
        String sql="update book set userName=?,userStatus=? where userId=?";
        //调用对象方法
        int[] ints =jdbcTemplate.batchUpdate(sql,bookList);
        System.out.println(Arrays.toString(ints));
    }

测试类:

//        批量修改
        List<Object[]> bookList=new ArrayList<>();
        Object[] o1={"hadoop","d","4"};
        Object[] o2={"spark","e","5"};
        Object[] o3={"linux","f","6"};
        bookList.add(o1);
        bookList.add(o2);
        bookList.add(o3);
        bookService.batchUpdate(bookList);
    }

结果:

 

  4.JdbcTemplate实现批量删除操作

    @Override
    public void batchDeleteBook(List<Object[]> listId) {
        //创建sql语句
        String sql="delete from book where userId=?";
        //调用对象方法
        int[] ints = jdbcTemplate.batchUpdate(sql, listId);
        System.out.println(Arrays.toString(ints));

    }

测试类:

        List<Object[]> bookList=new ArrayList<>();
        Object[] o1={"4"};
        Object[] o2={"5"};
        Object[] o3={"6"};
        bookList.add(o1);
        bookList.add(o2);
        bookList.add(o3);
        bookService.batchDelete(bookList);
    }

结果:

 事务

1.什么是事务

(1)事务是数据库操作的最基本单元,逻辑上的一组操作,要么都成功要么都失败

(2)经典场景:银行转账

2.事务的四大特性ACID:

(1)原子性:

(2)一致性:

(3)隔离性:

(4)持久性:

 1.创建数据库表,添加记录

 2.创建service,搭建dao,完成对象创建和注入关系

(1)service注入dao,dao注入jdbcTemplate注入DataSource

@Service
public class UserService {


//    注入dao
    @Autowired
    private UserDao userDao;

}
@Repository
public class UserDaoImpl implements UserDao{

    @Autowired
    private JdbcTemplate jdbcTemplate;
}
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!--        注入dataSource-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>

3.在dao里面创建两个方法:多钱方法和少钱方法;在service创建转账方法

dao里面的方法

    @Override
    public void addMoney() {
        //创建sql语句
        String sql="update account set money=money-? where username=?";
        //调用jdbcTemplate对象方法
        int cht = jdbcTemplate.update(sql, 100, "cht");
    }

    //少钱方法
    @Override
    public void reduceMoney() {
        //创建sql语句
        String sql="update account set money=money+? where username=?";
        //调用jdbcTemplate对象方法
        int hyj = jdbcTemplate.update(sql, 100, "hyj");

    }

service里面的方法

@Service
public class UserService {


//    注入dao
    @Autowired
    private UserDao userDao;

    public void transfer(){
//        cht少100
        userDao.reduceMoney();
//        hyj多100
        userDao.addMoney();
    }

}

测试类:

    @Test
    public void testAccount(){
        ApplicationContext context=
                new ClassPathXmlApplicationContext("bean1.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.transfer();
    }

运行结果:

 4.上面代码如果正常执行是没有问题的 但是如果有异常就会出现问题

        如下

    public void transfer(){
//        cht少100
        userDao.reduceMoney();
        
        //模拟异常  
        int i=10/0;
        
//        hyj多100
        userDao.addMoney();
    }

结果:

 上面的问题用事务来解决

 事务操作(Spring事务管理介绍)

1.事务添加到javaEE三层结构里面Service层(业务逻辑层)

2.在Spring进行事务管理操作

(1)有两种方式:编程式事务管理和声明式事务管理

3.声明式事务管理

(1)基于注解方式(使用)

(2)基于xml配置文件

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

5.Spring事务管理API

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

事务操作(注解声明式事务管理)

1.在Spring配置文件中配置事务管理器

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

2.在Spring配置文件中,开启事务注解

(1)在配置文件中引入名称空间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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

(2)开启事务注解

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

3.在servicer类上面(获取service类里面方法上面)添加一个事务注解

(1)@Transactional,这个注解添加到类上面,也可以添加到方法上面

(2)如果把这个注解添加到类上面,这个类里面所有的方法都添加事务

(3)如果把这个注解添加到方法上面,为这个方法添加事务

 测试结果数据不变:

 实事务操作(声明式事务管理参数配置)

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

2.propagation:事务传播行为

 

3.ioslation:事务隔离级别

(1)事务有隔离性,多事务操作之间不会产生影响,不考虑隔离性会产生很多问题

(2)有三个都问题:脏读、不可重复读、幻读

(3)脏读:一个未提交事务读取到另一个未提交事务的数据

         不可重复读:一个未提交的事务读取到另一个提交修改事务的数据

          幻读:一个未提交的事务读取到另一个提交添加事务的操作

(4)解决:通过设置事务的隔离级别,解决读问题

         隔离级别:

                        读未提交

                        读提交

                        可重复读

                        串行化

4.timeout:超时时间

(1)事务需要在一定的时间内提交否则就回滚

(2)默认值为-1,设置时间以秒为单位进行计算

5.readOnly:只读

(1)读:查询操作  写:修改删除操作

(2)readOnly默认值false,表示可以查询,可以添加修改操作

(3)设置readOnly值为true,设置成true之后,只能查询

6.rollbackFor:回滚

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

7.noRollbackFor:不回滚

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

事务操作(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:tx="http://www.springframework.org/schema/tx"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd
                            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--    开启组件扫描-->
    <context:component-scan base-package="com.atubo.spring"></context:component-scan>

    <!--    配置连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="jdbc:mysql://localhost:13306/userdb"/>
        <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:advice id="txadvice">
<!--        配置事务参数-->
        <tx:attributes>
<!--            指定哪种规则的方法上面添加事务-->
            <tx:method name="transfer" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置切入点和切面-->
    <aop:config>
<!--        配置切点-->
        <aop:pointcut id="pt" expression="execution(* com.atubo.spring.service.UserService.*(..))"/>
<!--        配置切面-->
        <aop:advisor advice-ref="txadvice" pointcut-ref="pt"/>
    </aop:config>
</beans>

事务操作(全注解)

package com.atubo.spring.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//配置类
@ComponentScan(basePackages = "com.atubo.spring")//组件扫描
@EnableTransactionManagement//开启事务
public class TxConfig {

    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:13306/userdb");
        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;
    }
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值