Spring (java后端框架,概述详细,由浅入深)

1.spring概述

Spring 的主要作用就是为代码“解耦”,降低代码间的耦合度。根据功能的不同,可以将一个系统中的代码分为主业务逻辑与系统级业务逻辑两类。它们各自具有鲜明的特点:主业务代码间逻辑联系紧密,有具体的专业业务应用场景,复用性相对较低;系统级业务相对功能独立,没有具体的专业业务应用场景,主要是为主业务提供系统级服务,如日志、安全、事务等,复用性强。

Spring 根据代码的功能特点,将降低耦合度的方式分为了两类:IoC 与 AOP。IOC 使得主
业务在相互调用过程中,不用再自己维护关系了,即不用再自己创建要使用的对象了。而是由 Spring 容器统一管理,自动“注入”。而 AOP 使得系统级服务得到了最大复用,且不用再由程序员手工将系统级服务“混杂”到主业务逻辑中了,而是由 Spring 容器统一完成“织入”。Spring 是于 2003 年兴起的一个轻量级的 Java 开发框架,它是为了解决企业应用开发的复杂性而创建的。Spring 的核心是控制反转(IoC)和面向切面编程(AOP)。简单来说,Spring是一个分层的 Java SE/EE full-stack(一站式)轻量级开源框架。
---- 百度百科《Spring》

Spring体系结构

在这里插入图片描述

Spring 有两个核心部分:IOC 和 Aop

(1)IOC:控制反转,把创建对象过程交给 Spring 进行管理
(2)Aop:面向切面,不修改源代码进行功能增强

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

2ioc bean管理(基于xml方式实现)

maven中引入spring依赖包

1.1spring.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.example</groupId>
	<artifactId>mybatis</artifactId>
	<version>1.0-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.9</maven.compiler.source>
		<maven.compiler.target>1.9</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>

<!-- spring 依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>

<!-- 测试依赖-->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.7.0</version>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>


	</build>
</project>

1.2User实体类

public class User {
    
    
    public  void  doMethods(){
    
    
        System.out.println("doMethods方法被调用了");
    }

}

1.3.测试方法

    @Test
    void doMethods() {
    
    
        //加载spring配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        //获取配置创建对象
        User user = (User)context.getBean("user");
        System.out.println(user);
        user.doMethods();
    }

ioc原理解析

底层用的技术: xml解析 ,反射 ,工厂模式

普通创建对象的方式和工厂类创建对象的模式

在这里插入图片描述ICO过程
在这里插入图片描述
1、IOC 思想基于 IOC 容器完成,IOC 容器底层就是对象工厂

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

(1)BeanFactory:IOC 容器基本实现,是 Spring 内部的使用接口,不提供开发人员进行使用

  • 加载配置文件时候不会创建对象,在获取对象(使用)才去创建对象

(2)ApplicationContext:BeanFactory 接口的子接口,提供更多更强大的功能,一般由开发人员进行使用.

  • 加载配置文件时候就会把在配置文件对象进行创建

BeanFactory 接口容器

BeanFactory 接口对象也可作为 Spring 容器出现。BeanFactory 接口是 ApplicationContext
接口的父类

而 Spring 配置文件以资源 Resouce 的形式出现在 XmlBeanFactory 类的构造器参数中。
Resouce 是一个接口,其具有两个实现类:
ClassPathResource:指定类路径下的资源文件
FileSystemResource:指定项目根路径或本地磁盘路径下的资源文件。
在这里插入图片描述在创建了 BeanFactory 容器后,便可使用其重载的 getBean()方法,从容器中获取指定的
Bean 对象。

两个接口容器的区别

虽然这两个接口容器所要加载的 Spring 配置文件是同一个文件,但在代码中的这两个容
器对象却不是同一个对象,即不是同一个容器:它们对于容器内对象的装配(创建)时机是
不同的。
装配时机测试时需要注意,首先要在容器中对象 StudentServiceImpl 类的无参构造器中
添加一个输出语句,以显示其是否执行。

bean管理操作的两种方式

1.基于xml配置文件
在这里插入图片描述
1.1: 在spring配置文件中,使用bean标签,在bean标签里面添加对应的属性,就可以实现对象的创建
1.2: bean标签常用属性
di 属性:获取对象的唯一标识
class属性:包类路径名
1.3 在创建对象的时候 也是默认的去执行无参构造方法,默认自带无参构造方法,如果声明了有参构造方法,如果不做特别声明,无参构造方法就会消失.
1.4基于xml注入属性: set方法注入和有参构造方法注入

通过set方式注入属性

    <bean id="book" class="com.maven.spring.bean.Book">
        <property name="name" value="java入门"></property>
        <property name="author" value="卡夫卡"></property>
    </bean>
    <!-- 使用set给对象属性赋值 -->
    

通过有参构造方法在创建对象的时候给对象赋值

    <bean id="book" class="com.maven.spring.bean.Book">
        <!-- 使用有参构造方法给对象属性赋值 -->
        <constructor-arg index="0" value="java入门"/>
        <constructor-arg index="1" value="卡夫卡"/>
    </bean>

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

1.字面量null值

       <constructor-arg name="author" >
            <null/>
        </constructor-arg>

2.字面量值包含特殊符号

<!-- 2 把带特殊符号内容写到 <![CDATA[特殊符号值]]> 中 -->
<property name="name">
<value> <![CDATA[<<南京>>]]> </value>
</property>

3.注入属性-外部 bean
3.1配置文件

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

    <bean id="UserDaoImpl" class="com.maven.spring.dao.impl.UserDaoImpl"></bean>

3.2dao接口

public interface UserDao {
    
    
    /**
     * 注入属性外部
     */
    void update();

}

3.3dao接口的实现类

public class UserDaoImpl implements UserDao {
    
    
    /**
     * 注入属性外部
     */


    @Override
    public void update() {
    
    
        System.out.println("修改成功");
    }
}

3.4service类

public class UserService {
    
    

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

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

    public  void login(){
    
    
        userDao.update();
        System.out.println("登录成功");
    }
}

3.5测试方法

   @Test
    void login() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.login();
    }

4.内部注入bean
4.1spring.xml配置文件

<!--内部 bean-->
<bean id="emp" class="com.maven.spring.bean.Emp" > <!--创建Emp对象-->
    <property name="name" value="张三"> </property> <!--给Emp对象属性赋值-->
    <property name="sex" value=""> </property>

<!-- 设置对象类型属性-->
    <property name="dept" >  <!-- 创建Dep对象 -->
    <bean id="dept" class="com.maven.spring.bean.Dept" >
        <property name="name" value="安全部"> </property> <!-- 给Dep对象赋值 -->
    </bean>
    </property>
</bean>

4.2 Emp和Dep类

Dept

public class Dept {
    
    

    //部门类
    private  String name;

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

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

Emp

public class Emp {
    
    
    //员工类
    private String name;
    private String  sex;

    //员工表示某一个部门 使用对象形式表示
    private  Dept dept;

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

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

    public void setSex(String sex) {
    
    
        this.sex = sex;
    }
    public void init(){
    
    
        System.out.println(name+","+sex+","+dept);
    }
}

4.3测试方法

    //内部bean
    @Test
    void internalBean() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Emp emp = context.getBean("emp", Emp.class);
        emp.init();

    }

级联bean第二种写法

<!--级联 bean-->
    <bean id="emp" class="com.maven.spring.bean.Emp" > <!--创建Emp对象-->
        <property name="name" value="张三"> </property> <!--给Emp对象属性赋值-->
        <property name="sex" value=""> </property>

        <!--设置对象类型属性-->
        <property name="dept"  ref="dept">  <!-- 创建Dep对象 --></property>
        <property name="dept.name"  value="技术部">  <!-- 创建Dep对象 --></property>
   </bean>

    <bean id="dept" class="com.maven.spring.bean.Dept" > </bean>

但是前提是: Emp中的生成get方法

    public Dept getDept() {
    
    
        return dept;
    }

5.注入集合类型属性
5.1Student类

public class Student {
    
    
    //数组属性类型
    private  String courses [] ;
    //list集合
    private List<String> students;
    //map集合
    private Map<String,String> map;
    //set集合
    private Set sets;

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

    public void setStudents(List<String> students) {
    
    
        this.students = students;
    }

    public void setMap(Map<String, String> map) {
    
    
        this.map = map;
    }

    public void setSets(Set sets) {
    
    
        this.sets = sets;
    }
    public void init() {
    
    
        System.out.println(Arrays.toString(courses));
        System.out.println("ArrayList:"+students);
        System.out.println("Set:"+sets);
        System.out.println("Map:"+map);


    }

}

5.2bean.xml配置文件

<bean id="student" class="com.maven.spring.bean.Student">
    <!-- 注入数组类型 -->
    <property name="courses">
        <array>
            <value>java课程</value>
            <value>大数据</value>
        </array>
    </property>
    <!-- 注入List集合类型 -->
    <property name="students" >
        <list>
            <value>linux</value>
            <value>运维工程师</value>
        </list>
    </property>
<!--  注入Map集合类型-->
    <property name="map">
        <map>
            <entry key="xiaoming" value=""></entry>
            <entry key="zhangsan" value=""></entry>
        </map>
    </property>
    <!--  注入Set集合类型-->
    <property name="sets" >
     <set>
         <value>javaSe</value>
         <value>javaEE</value>
     </set>
    </property>
</bean>

5.3测试方法


//通过xml注入复杂数据类型
    @Test
    void doMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = context.getBean("student", Student.class);
        student.init();
    }

6.ArrayList中注入对象
6.1Course和Student

public class Course {
    
    
    private  String course;

    public void setCourse(String course) {
    
    
        this.course = course;
    }

    @Override
    public String toString() {
    
    
        return "Course{" +
                "course='" + course + '\'' +
                '}';
    }
}
public class Student {
    
    
    //数组属性类型
    private  String courses [] ;
    //list集合
    private List<String> students;
    //map集合
    private Map<String,String> map;
    //set集合
    private Set sets;

    private List<Course> courseList;

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

    public void setStudents(List<String> students) {
    
    
        this.students = students;
    }

    public void setMap(Map<String, String> map) {
    
    
        this.map = map;
    }

    public void setSets(Set sets) {
    
    
        this.sets = sets;
    }

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

    public void init() {
    
    
        System.out.println(Arrays.toString(courses));
        System.out.println("ArrayList:"+students);
        System.out.println("Set:"+sets);
        System.out.println("Map:"+map);
        System.out.println("courseList:"+courseList);


    }

}

6.2 bea.xml配置

<bean id="student" class="com.maven.spring.bean.Student">
    <!-- 注入数组类型 -->
    <property name="courses">
        <array>
            <value>java课程</value>
            <value>大数据</value>
        </array>
    </property>
    <!-- 注入List集合类型 -->
    <property name="students" >
        <list>
            <value>linux</value>
            <value>运维工程师</value>
        </list>
    </property>
<!--  注入Map集合类型-->
    <property name="map">
        <map>
            <entry key="xiaoming" value=""></entry>
            <entry key="zhangsan" value=""></entry>
        </map>
    </property>
    <!--  注入Set集合类型-->
    <property name="sets" >
     <set>
         <value>javaSe</value>
         <value>javaEE</value>
     </set>
    </property>

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

    <bean id="course1" class="com.maven.spring.bean.Course">
         <property name="course" value="spring"></property>
    </bean>

    <bean id="course2" class="com.maven.spring.bean.Course">
        <property name="course" value="mybatis"></property>
    </bean>

6.3 测试方法

    @Test
    void objectInfuseMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Student student = context.getBean("student", Student.class);
        student.init();

    }

7.提取list集合类型属性注入
7.1bean类

//把集合注入类型部分抽取出来
public class Book {
    
    
    private List<String> list;

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

    public  void  init(){
    
    
        for (String str: list) {
    
    
            System.out.println("List集合中的字符串:"+str);
        }
    }
}


7.2bean.xml

    <!--1 提取list集合类型属性注入-->
    <util:list id="bookList">
        <value>java</value>
        <value>python</value>
        <value>javaScript</value>
    </util:list>

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

7.3测试方法

    //提取list集合类型属性注入使用
    @Test
    void publicListMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.init();


    }

8.IOC 操作 Bean 管理(FactoryBean)
8.1 myBean 实体类


public class MyBean  implements FactoryBean {
    
    
    @Override
    public Object getObject() throws Exception {
    
    
        Course course = new Course();
        course.setCourse("java基础");

        return course;
    }

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

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

8.2 配置文件

<!--工厂bean 返回的类型可以和设置的类型不一致-->
    <bean id="myBean" class="com.maven.spring.bean.MyBean">

8.3 测试方法

//工厂bean 返回的类型可以和设置的类型不一致
   /**
     * 普通 bean:在配置文件中定义 bean 类型就是返回类型
     * 工厂 bean:在配置文件定义 bean 类型可以和返回类型不一样
     */
    @Test
    void factoryBeanMethods() {
    
    
    //加载spring配置文件的时候创建就对象
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
    Course course = context.getBean("myBean", Course.class);
        System.out.println(course);


    }

9.IOC 操作 Bean 管理(bean 作用域)
1、在 Spring 里面,设置创建 bean 实例是单实例还是多实例
2、在 Spring 里面,默认情况下,bean 是单实例对象
在这里插入图片描述

<bean id="student" class="com.maven.spring.bean.Student">
    <!-- 注入数组类型 -->
    <property name="courses">
        <array>
            <value>java课程</value>
            <value>大数据</value>
        </array>
    </property>
    <!-- 注入List集合类型 -->
    <property name="students" >
        <list>
            <value>linux</value>
            <value>运维工程师</value>
        </list>
    </property>
<!--  注入Map集合类型-->
    <property name="map">
        <map>
            <entry key="xiaoming" value=""></entry>
            <entry key="zhangsan" value=""></entry>
        </map>
    </property>
    <!--  注入Set集合类型-->
    <property name="sets" >
     <set>
         <value>javaSe</value>
         <value>javaEE</value>
     </set>
    </property>

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

    <bean id="course1" class="com.maven.spring.bean.Course">
         <property name="course" value="spring"></property>
    </bean>

    <bean id="course2" class="com.maven.spring.bean.Course">
        <property name="course" value="mybatis"></property>
    </bean>

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

9.1 Book类

public class Book {
    
    

}

9.2 xml配置文件

<!-- 设置为多实例 -->
    <bean id="book" class="com.maven.spring.bean.Book" scope="prototype"> </bean>

9.3测试方法

// 多实例
    @Test
    void moreInstanceMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
        Book book1 = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);
        System.out.println(book1);
        System.out.println(book2);

    }

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

public class Orders {
    
    
    private String name;

    public void setName(String name) {
    
    
        System.out.println("2:掉用set方法,赋值");
        this.name = name;
    }

    public Orders() {
    
    
        System.out.println("1:执行无参构造方法,创建对象");
    }

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

    public  void  destroyMethod(){
    
    
        System.out.println("5:销毁创建出来的bean对象");
    }
}

10.2 配置xml文件

<bean id="orders" class="com.maven.spring.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
    <property name="name" value="电脑"> </property>
</bean>

10.3 测试方法

 @Test
    void lifeCycleMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Orders order = context.getBean("orders", Orders.class);
        System.out.println("4:获取创建出来的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 的销毁的方法(需要进行配置销毁的方法)

10.1 bean类

public class Orders {
    
    
    private String name;

    public void setName(String name) {
    
    
        System.out.println("2:掉用set方法,赋值");
        this.name = name;
    }

    public Orders() {
    
    
        System.out.println("1:执行无参构造方法,创建对象");
    }

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

    public  void  destroyMethod(){
    
    
        System.out.println("7:销毁创建出来的bean对象");
    }
}
------------------------分割线-----------------------------------
public class MyBeanPost implements BeanPostProcessor {
    
    
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("3:在我们初始化之前执行的方法");
        return null;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    
    
        System.out.println("5:在我们初始化之后执行的方法");
        return null;
    }
}

10.2 配置xml文件

<bean id="orders" class="com.maven.spring.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
    <property name="name" value="电脑"> </property>
</bean>
<!-- 配置后置处理器 -->
    <bean id="myBeanPost" class="com.maven.spring.bean.MyBeanPost"></bean>

10.3 测试方法

//bean生命周期
    @Test
    void lifeCycleMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
        Orders order = context.getBean("orders", Orders.class);
        System.out.println("6:获取创建出来的bean实例对象");
        //手动销毁创建出来的实例对象
        context.close();


    }

11.IOC 操作 Bean 管理(xml 自动装配)
11.11 bean类

public class Dept {
    
    

}
----------------------------------------------------------------------
public class Emp {
    
    
    private  Dept dept;

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

    @Override
    public String toString() {
    
    
        return "Emp{" +
                "dept=" + dept +
                '}';
    }
    public  void  test(){
    
    
        System.out.println("dept对象:"+dept);
    }
}

11.2 配置文件

<!-- 实现自动装配
byName :根据属性名称进行注入 注入bean的id值和属性名称要一致
byType:根据属性类型进行自动注入

-->
    <bean id="emp" class="com.maven.spring.autowire.Emp" autowire="byName">
<!--    <property name="dept" ref="dept"> </property>-->
    </bean>

    <bean id="dept" class="com.maven.spring.autowire.Dept"> </bean>

11.3 测试方法

    //自动装配创建对象
    @Test
    void autoConfigMethods() {
    
    
        //加载spring配置文件的时候创建就对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean5.xml");
        Emp emp = context.getBean("emp", Emp.class);
        emp.test();
        System.out.println(emp);



    }

3.ioc bean管理(基于注解方式实现)

1、什么是注解
(1)注解是代码特殊标记,格式:@注解名称(属性名称=属性值, 属性名称=属性值…)
(2)使用注解,注解作用在类上面,方法上面,属性上面
(3)使用注解目的:简化 xml 配置
2、Spring 针对 Bean 管理中创建对象提供注解
(1)@Component 都可以
(2)@Service service层
(3)@Controller web层
(4)@Repository dao层

  • 上面四个注解功能是一样的,都可以用来创建 bean 实例

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

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

第二步 开启组件扫描
开启组件扫描

  <context:component-scan base-package="com.maven.spring.dao,com.maven.spring.service" />

1 如果扫描多个包,多个包使用逗号隔开
2 扫描包上层目录

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

在注解里面 value 属性值可以省略不写,
默认值是类名称,首字母小写
UserService – userService

1. 基于注解方式创建对象的第一个实例

1.1 bean类

/**
 * 在注解里面 value属性值可以不写 如果不写就是 默认类名的第一个首字母小写
 */
@Component(value = "userService")
public class UserService {
    
    
    public  void add(){
    
    
        System.out.println(" 成功创建UserService的实例对象");
    }
}

1.2 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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:component-scan base-package="com.maven.spring" />

</beans>

1.3 测试方法

    //使用注解的方式创建对象
    @Test
    void serviceAnnotationMethods() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        System.out.println(userService);



    }


2.开启配置扫描的细节做法

2.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: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
">
<!-- 开启组件扫描  扫描com.maven.spring包中所有的类-->
    <context:component-scan base-package="com.maven.spring" />


</beans>

2.2扫描包中指定的内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">
<!-- 开启组件扫描  扫描com.maven.spring包中所有的类-->

<!--  use-default-filters="false":表示不使用默认的filter 使用我们自定义的filter
      context:include-filter:设置扫描哪些内容
      type:根据注解来扫描
      expression="org.springframework.stereotype.Component":扫描注解中带有Component注解的类
-->
<context:component-scan base-package="com.maven.spring" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>


2.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: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
">
<!-- 开启组件扫描  扫描com.maven.spring包中所有的类-->

<!-- 示例1:  use-default-filters="false":表示不使用默认的filter 使用我们自定义的filter
      context:include-filter:设置扫描哪些内容
      type:根据注解来扫描
      expression="org.springframework.stereotype.Component":扫描注解中带有Component注解的类
-->
<context:component-scan base-package="com.maven.spring" use-default-filters="false">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>

3.基于注解的方式进行属性注入(根据属性类型进行自动装配)

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

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

3.1 bean类

//Dao接口
public interface UserDao {
    
    
    public void  add();
}

//Dao接口实现类---------------------------------------------------------------------------------

@Repository(value = "userDaoImpl")  //创建UserDaoImpl 对象
public class UserDaoImpl implements UserDao {
    
    

    @Override
    public void add() {
    
    
        System.out.println("dao add.....");
    }
}
//Service 类-------------------------------------------------------------------------------
/**
 * 在注解里面 value属性值可以不写 如果不写就是 默认类名的第一个首字母小写
 */
@Service(value = "userService") //创建userService对象
public class UserService {
    
    
    // 不需要添加set方法 添加注解属性即可
    @Autowired //根据类型进行注入
    private UserDao userDao;

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

3.2配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">
<!-- 开启组件扫描  扫描com.maven.spring包中所有的类-->
    <context:component-scan base-package="com.maven.spring" />


</beans>

3.3测试方法

   //使用注解的方式创建对象 并且给对象的属性赋值(自动按类型装配)
    @Test
    void autoConfigAttributeAnnotationMethods() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        System.out.println(userService);

    }

4.@Qualifier:根据名称进行注入
这个@Qualifier 注解的使用,和上面@Autowired 一起使用
4.1bean类

//UserDao 接口
public interface UserDao {
    
    
    public void  add();
}
//UserDao的实现类
@Repository(value = "userDaoImpl")  //创建UserDaoImpl 对象
public class UserDaoImpl implements UserDao {
    
    

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

//service层类
/**
 * 在注解里面 value属性值可以不写 如果不写就是 默认类名的第一个首字母小写
 */
@Service(value = "userService") //创建userService对象
public class UserService {
    
    
    // 不需要添加set方法 添加注解属性即可
    @Autowired    //根据类型进行注入
    @Qualifier(value = "userDaoImpl")    //根据属性名进行注入属性
    private UserDao userDao;

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

4.2 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       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
">
<!-- 开启组件扫描  扫描com.maven.spring包中所有的类-->
    <context:component-scan base-package="com.maven.spring" />


</beans>

4.3测试方法

    //使用注解的方式创建对象 并且给对象的属性赋值(按属性名进行装配)
    @Test
    void autoConfigAttributeAnnotationMethods() {
    
    
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        System.out.println(userService);

    }

5. @Resource:可以根据类型注入,可以根据名称注入

@Resource   //根据类型进行注入
@Resource(name = "userDaoImpl") //根据名称进行注入

6. @Value:注入普通类型属性

@Value(value = "字符串值")
private String name;

7、完全注解开发

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

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

}

(2)编写测试类

  //使用注解的方式创建对象 并且给对象的属性赋值(使用注解配置类 代替xml配置文件)
    @Test
    void configClassMethods() {
    
    
       ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
        System.out.println(userService);

    }

4.AOP(面向切面编程)

1、什么是 AOP
(1)面向切面编程(方面),利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得
业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
(2)通俗描述:不通过修改源代码方式,在主干功能里面添加新功能
(3)使用登录的例子举例说明
在这里插入图片描述AOP(底层原理)
1、AOP 底层使用动态代理
在这里插入图片描述AOP(术语)
1、连接点
类里面有哪些方法可以被增强,这些方法被称为连接点
2、切入点
实际被增强的方法,叫做切入点
3、通知(增强)
实际被增强的逻辑部分称为通知
通知的类型:
1.前置通知
2.后置通知
3.环绕通知
4.异常通知
5.最终通知
4、切面
是通知:是把通知应用到切入点的过程
AOP 操作(准备工作)
(1)AspectJ 不是 Spring 组成部分,独立 AOP 框架,一般把 AspectJ 和 Spirng 框架一起使
用,进行 AOP 操作.
2、基于 AspectJ 实现 AOP 操作
(1)基于 xml 配置文件实现
(2)基于注解方式实现(使用)
3、在项目工程里面引入 AOP 相关依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.example</groupId>
	<artifactId>mybatis</artifactId>
	<version>1.0-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>


<!-- spring 依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>

<!-- 测试依赖-->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.7.0</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.20</version>
		</dependency>
<!--aop 切面需要的依赖 -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>net.sourceforge.cglib</groupId>
			<artifactId>com.springsource.net.sf.cglib</artifactId>
			<version>2.2.0</version>
		</dependency>

		<dependency>
			<groupId>org.aopalliance</groupId>
			<artifactId>com.springsource.org.aopalliance</artifactId>
			<version>1.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>com.springsource.org.aspectj.weaver</artifactId>
			<version>1.6.4.RELEASE</version>
		</dependency>

	</dependencies>

	<build>


	</build>
</project>

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

2)语法结构: execution([权限修饰符] [返回类型] [类全路径] [方法名称]([参数列表]) )
举例 1:对 com.atguigu.dao.BookDao 类里面的 add 进行增强
execution(* com.atguigu.dao.BookDao.add(..))
举例 2:对 com.atguigu.dao.BookDao 类里面的所有的方法进行增强
execution(* com.atguigu.dao.BookDao.* (..))
举例 3:对 com.atguigu.dao 包里面所有类,类里面所有方法进行增强
execution(* com.atguigu.dao.*.* (..))

AOP 操作(AspectJ 注解)
1、创建类,在类里面定义方法

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

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


//增强类
@Component //生成 UserProxy 对象
@Aspect //生成代理对象
public class UserProxy {
    
    
    @Before(value = "execution(* com.maven.spring.aopanno.User.add(..))") //前置通知注解
    public  void before(){
    
    
        //前置通知
        System.out.println("before......");
    }
}

3、进行通知的配置
(1)在 spring 配置文件中,开启注解扫描
在这里插入图片描述

(2)使用注解创建 User 和 UserProxy 对象
在这里插入图片描述

(3)在增强类上面添加注解 @Aspect
在这里插入图片描述

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

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

//增强类
@Component //生成 UserProxy 对象
@Aspect() //生成代理对象
public class UserProxy {
    
    
    @Before(value = "execution(* com.maven.spring.aopanno.User.add(..))") //前置通知注解
    public  void before(){
    
    
//前置通知
        System.out.println("before 前置通知...... 在被增强的方法之前执行");
    }

    @AfterReturning(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  AfterReturning(){
    
    
//后置通知
        System.out.println("AfterReturning 后置通知...... 在增强方法之后执行 当程序出现异常的时候不执行该方法 ");
    }


    @After(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  after(){
    
    
//最终通知
        System.out.println("after 最终通知...... 无论程序出现什么结果 都会执行该方法 在add方法返回结果后的时候执行");
    }

    @AfterThrowing(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  AfterThrowing(){
    
    
//异常通知
        System.out.println("AfterThrowing 异常通知......add方法出现异常的时候执行");
    }

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

5、相同的切入点抽取

//增强类
@Component //生成 UserProxy 对象
@Aspect() //生成代理对象
public class UserProxy {
    
    
  //公共切入点的好处;使代码更加灵活,以后代码发生改变,只需要改此处就可以
    @Pointcut(value = "execution(* com.maven.spring.aopanno.User.add(..))") //公共切入点抽取
    public void pointcut(){
    
    

    }

    @Before(value = "pointcut()") //前置通知注解 (调用公共切入点的值)
    public  void before(){
    
    

//前置通知
        System.out.println("before 前置通知...... 在被增强的方法之前执行");
    }

    @AfterReturning(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  AfterReturning(){
    
    
//后置通知
        System.out.println("AfterReturning 后置通知...... 在增强方法之后执行 当程序出现异常的时候不执行该方法 ");
    }


    @After(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  after(){
    
    
//最终通知
        System.out.println("after 最终通知...... 无论程序出现什么结果 都会执行该方法 在add方法返回结果后的时候执行");
    }

    @AfterThrowing(value = "execution(* com.maven.spring.aopanno.User.add(..) )")
    public void  AfterThrowing(){
    
    
//异常通知
        System.out.println("AfterThrowing 异常通知......add方法出现异常的时候执行");
    }

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

6、有多个增强类多同一个方法进行增强,设置增强类优先级
(1)在增强类上面添加注解 @Order(数字类型值),数字类型值越小优先级越高
在这里插入图片描述在这里插入图片描述
7、完全使用注解开发
(1)创建配置类,不需要创建 xml 配置文件

@Configuration
@ComponentScan(basePackages = {
    
    "com.maven.spring.aopanno"}) //开启注解扫描 创建对象
@EnableAspectJAutoProxy(exposeProxy = true)  //开启Aspect生成代理对象
public class AopConfig {
    
    
}

测试方法

    //AOP 操作(AspectJ 注解)2 完全注解开发
    @Test
    void aopAnnotationMethods2() {
    
    

        ApplicationContext context = new AnnotationConfigApplicationContext(AopConfig.class);
        User user = context.getBean("user", User.class);
        user.add();

    }

8.xml方式aop切面编程
1.被增强类

public class Book {
    
    
    public  void  buy(){
    
    
        System.out.println("buy ...........");
    }
}

2.增强类


public class BookProxy {
    
    
    public  void before(){
    
    
        System.out.println("buy ...之前执行的方法");
    }
}

3.测试方法

    //AOP 操作(AspectJ 注解)3 xml配置开发
    @Test
    void aopAnnotationMethods3() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        Book book = context.getBean("book", Book.class);
        book.buy();
    }

4配置文件

<?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.maven.spring.aopanno.Book"></bean>
    <bean id="bookProxy" class="com.maven.spring.aopanno.BookProxy"></bean>

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

</beans>

5.JdbcTemplate

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

准备好数据库表 book
在这里插入图片描述
1.1准备工作导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
		 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>org.example</groupId>
	<artifactId>mybatis</artifactId>
	<version>1.0-SNAPSHOT</version>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<maven.compiler.source>1.8</maven.compiler.source>
		<maven.compiler.target>1.8</maven.compiler.target>
	</properties>

	<dependencies>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.2</version>
		</dependency>


<!-- spring 依赖 -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>

<!-- 测试依赖-->
		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.7.0</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.20</version>
		</dependency>
<!--aop 切面需要的依赖 -->

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>net.sourceforge.cglib</groupId>
			<artifactId>com.springsource.net.sf.cglib</artifactId>
			<version>2.2.0</version>
		</dependency>

		<dependency>
			<groupId>org.aopalliance</groupId>
			<artifactId>com.springsource.org.aopalliance</artifactId>
			<version>1.0.0</version>
		</dependency>

		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>com.springsource.org.aspectj.weaver</artifactId>
			<version>1.6.4.RELEASE</version>
		</dependency>

<!--数据库连接池-->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.2.3</version>
		</dependency>
<!--mysql驱动-->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.21</version>
		</dependency>
<!--spring对jdbc的封装-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>
<!--spring整合其他框架的使用-->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>5.2.6.RELEASE</version>
		</dependency>
	</dependencies>

	<build> </build>
</project>

1.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
">
<!-- 开启组件扫描   -->
    <context:component-scan base-package="com.maven.spring"> </context:component-scan>

<!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
        <property name="url" value="jdbc:mysql://localhost/book_ctiy?serverTimezone=GMT%2B8"> </property>
        <property name="username" value="root"> </property>
        <property name="password" value="2732195202"> </property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"> </property>
    </bean>
<!--    配置 JdbcTemplate 对象,注入 DataSource -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"  >
<!-- 将数据库连接池的信息注入到 dataSource 对象中-->
    <property name="dataSource" ref="dataSource"> </property>
    </bean>
</beans>

1.3 实体类


public class Book {
    
    

    private String userId;
    private  String username;
    private  String ustatus;

    public String getUserId() {
    
    
        return userId;
    }

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

    public String getUsername() {
    
    
        return username;
    }

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

    public String getUstatus() {
    
    
        return ustatus;
    }

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

    public Book(String userId, String username, String ustatus) {
    
    
        this.userId = userId;
        this.username = username;
        this.ustatus = ustatus;
    }

    public Book() {
    
    
    }

    @Override
    public String toString() {
    
    
        return "User{" +
                "userId='" + userId + '\'' +
                ", username='" + username + '\'' +
                ", ustatus='" + ustatus + '\'' +
                '}';
    }
}

1.4 写dao接口

public interface BookDao {
    
    

    /**
     * 添加图书
     * @param book 一个图书对象
     */
    void add(Book book);
}

1.5 实现dao接口


@Repository //创建BookDaoImpl对象
public class BookDaoImpl implements BookDao {
    
    

//注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 添加图书
     *
     * @param book 一个图书对象
     */
    @Override
    public void add(Book book) {
    
    
        //参数1 sql语句 ,参数2 设置sql语句中的值
        String sql = "insert into book values(?,?,?)";
        Object args [] ={
    
    book.getUserId(),book.getUsername(),book.getUstatus()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }
}

1.6 service层


@Repository //创建BookDaoImpl对象
public class BookDaoImpl implements BookDao {
    
    

//注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 添加图书
     *
     * @param book 一个图书对象
     */
    @Override
    public void add(Book book) {
    
    
        //参数1 sql语句 ,参数2 设置sql语句中的值
        String sql = "insert into book values(?,?,?)";
        Object args [] ={
    
    book.getUserId(),book.getUsername(),book.getUstatus()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }
}

1.7测试方法

    @Test
    void addBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book("123","admin","1");
        bookService.addBook(book);

    }

5.1 JdbcTemplate(常见的增删改查和批量操作)

1.数据库表还是上面哪一个
2.spring配置文件 和上面一样不变
3.maven依赖 和上面一样不变
4.实体类(bean) 和上面一致不变
5.dao接口

package com.maven.spring.dao;


import com.maven.spring.bean.Book;

import java.util.List;

public interface BookDao {
    
    

    /**
     * 添加图书
     * @param book 一个图书对象
     */
    void add(Book book);

    /**
     * 修改图书
     * @param book 一个图书对象
     */
    void updateBook(Book book);

    /**
     * 删除图书
     * @param id
     */
    void  deleteBook(String id);

    /**
     * 查询所有的图书
     * @return 返回一个List集合
     */
     List<Book> selectAllBook();


    /**
     * 查询book 中有多少条记录
     * @return 返回表中的总记录数
     */
    int selectTablesCount();

    /**
     * 查询book 按照条件查询
     * @return 返回表中满足条件的记录
     */
    List<Book> conditionsSelect(String ustatus);

    /**
     * 按条件查询某一条记录
     * @return 返回一个 book对象
     */
     Book selectBookObject(String id);

    /**
     * 按条件模糊查询
     * @return 返回一个List集合
     */
    List<Book> selectBookLike(String username);

    /**
     * 按条件模糊查询
     * @return 返回一个List集合
     */
    List<Book> selectBookPage(int begin, int stop );

    /**
     * 批量添加数据
     * @param batchArgs list集合数组
     */
     void batchAddBook(List<Object[]> batchArgs);

    /**
     *  批量修改数据
     * @param batchArgs list集合数组
     */
    void batchUpdateBook(List<Object[]> batchArgs);

    /**
     * 批量删除数据
     * @param batchArgs list集合数组
     */
    void batchDeleteBook(List<Object[]> batchArgs);
}

6.dao接口实现类



@Repository //创建BookDaoImpl对象
public class BookDaoImpl implements BookDao {
    
    

//注入jdbcTemplate
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 添加图书
     *
     * @param book 一个图书对象
     */
    @Override
    public void add(Book book) {
    
    
        //参数1 sql语句 ,参数2 设置sql语句中的值
        String sql = "insert into book values(?,?,?)";
        Object args [] ={
    
    book.getUserId(),book.getUsername(),book.getUstatus()};
        int update = jdbcTemplate.update(sql,args);
        System.out.println(update);
    }

    /**
     * 修改图书
     *
     * @param book 一个图书对象
     *
     */
    @Override
    public void updateBook(Book book) {
    
    
        String sql = "update book set ustatus=?,username=? where user_id=?";
        Object args [] ={
    
    book.getUsername(),book.getUstatus(),book.getUserId()};
        int updateCount = jdbcTemplate.update(sql, args);
        System.out.println(updateCount);
    }

    /**
     * 删除图书
     *
     * @param id
     */
    @Override
    public void deleteBook(String id) {
    
    
        String sql = "delete from book  where user_id=?";
        int updateCount = jdbcTemplate.update(sql, id);
        System.out.println(updateCount);
    }

    /**
     * 查询所有的图书
     *
     * @return 返回一个List集合
     */
    @Override
    public List<Book> selectAllBook() {
    
    
        String sql = "select * from book  ";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
        return bookList;
    }

    /**
     * 查询book 中有多少条记录
     *
     * @return 返回表中的总记录数
     */
    @Override
    public int selectTablesCount() {
    
    
        String sql = "select count(*) from book";
        int selectCount = jdbcTemplate.queryForObject(sql,Integer.class);
        return selectCount;
    }

    /**
     * 查询book 按照条件查询
     *
     * @return 返回表中满足条件的记录
     */
    @Override
    public  List<Book> conditionsSelect(String ustatus) {
    
    
        String sql = "select * from book where ustatus=?  ";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class),ustatus);
        return bookList;
    }

    /**
     * 查询返回一条记录 也就是一个对象
     *
     * @return 返回一个 book对象
     */
    @Override
    public Book selectBookObject(String id) {
    
    
        String sql = "select * from book where user_id=?  ";
        Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<Book>(Book.class), id);
        return book;
    }

    /**
     * 按条件模糊查询
     *
     * @param username
     * @return 返回一个List集合
     */
    @Override
    public List<Book> selectBookLike(String username) {
    
    
        String sql = "select * from book  where username like ?  ";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class),username);
        return bookList;

    }

    /**
     * 分页查询
     *
     * @param begin 开始位置索引
     * @param stop  结束位置索引
     * @return 返回一个List集合
     */
    @Override
    public List<Book> selectBookPage(int begin, int stop) {
    
    
        String sql = "select * from book  limit ?,?  ";
        List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class),begin,stop);
        return bookList;

    }

    /**
     * 批量添加数据
     *
     * @param batchArgs list集合数组
     */
    @Override
    public void batchAddBook(List<Object[]> batchArgs) {
    
    
        String sql = "insert into book values(?,?,?)";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    /**
     * 批量修改数据
     *
     * @param batchArgs list集合数组
     */
    @Override
    public void batchUpdateBook(List<Object[]> batchArgs) {
    
    
        String sql = "update book set username=?,ustatus=? where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }

    /**
     * 批量删除数据
     *
     * @param batchArgs list集合数组
     */
    @Override
    public void batchDeleteBook(List<Object[]> batchArgs) {
    
    
        String sql = "delete from book where user_id=?";
        int[] ints = jdbcTemplate.batchUpdate(sql, batchArgs);
        System.out.println(Arrays.toString(ints));
    }
}

7.service层

@Service //创建BookService对象
public class BookService {
    
    
    //注入Dao
    @Autowired
    private BookDao bookDao;

    //添加方法
    public void  addBook(Book book){
    
    
    bookDao.add(book);
    }

    /**
     * 修改图书
     * @param book 一个图书对象
     */
    public   void updateBook(Book book){
    
    

        bookDao.updateBook(book);

    }

    /**
     * 删除图书
     * @param id
     */
    public void  deleteBook(String id) {
    
    
     bookDao.deleteBook(id);
    }

    /**
     * 查询所有的图书
     * @return 返回一个List集合
     */
    public  List<Book> selectAllBook(){
    
    
        List<Book> bookList = bookDao.selectAllBook();
        return bookList;
    }

    /**
     * 查询book 中有多少条记录
     *
     * @return 返回表中的总记录数
     */
    public int selectTablesCount() {
    
    
        int count = bookDao.selectTablesCount();
        return count;
    }

    /**
     * 按条件查询表中满足条件的记录
     *
     * @return 返回一个List集合
     */
    public List<Book> selectConditions(String ustatus) {
    
    
        List<Book> bookList = bookDao.conditionsSelect(ustatus);
        return bookList;
    }

    /**
     * 按条件查询表中满足条件的某一条记录
     *
     * @return 返回一个Book对象
     */
    public Book selectBookObject(String id) {
    
    
        Book book = bookDao.selectBookObject(id);
        return book;
    }

    /**
     * 按条件模糊查询
     *
     * @param username
     * @return 返回一个List集合
     */

    public List<Book> selectBookLike(String username) {
    
    
        List<Book> bookList = bookDao.selectBookLike("%"+username+"%");
        return bookList;

    }

    /**
     * 分页查询
     *
     * @param begin 开始位置索引
     * @param stop  结束位置索引
     * @return 返回一个List集合
     */

    public List<Book> selectBookPage(int begin, int stop) {
    
    
        List<Book> bookList = bookDao.selectBookPage(begin, stop);
        return bookList;

    }


    /**
     * 批量添加数据
     *
     * @param batchArgs list集合数组
     */

    public void batchAddBook(List<Object[]> batchArgs) {
    
    
       bookDao.batchAddBook(batchArgs);
    }

    /**
     * 批量修改数据
     *
     * @param batchArgs list集合数组
     */

    public void batchUpdateBook(List<Object[]> batchArgs) {
    
    
       bookDao.batchUpdateBook(batchArgs);
    }

    /**
     * 批量删除数据
     *
     * @param batchArgs list集合数组
     */

    public void batchDeleteBook(List<Object[]> batchArgs) {
    
    
        bookDao.batchDeleteBook(batchArgs);
    }
}

8.测试类

 @Test
    void addBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book("123","admin","1");
        bookService.addBook(book);

    }
    @Test
    void delBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        bookService.deleteBook("123");

    }
    @Test
    void selectAllBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book("123","admin","1");
        bookService.addBook(book);

    }
    @Test
    void updateBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = new Book("123","user","0");
        bookService.updateBook(book);

    }

    @Test
    void selectTalesCount() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        int count = bookService.selectTablesCount();
        System.out.println(count);

    }

    @Test
    void selectBookAll() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Book> bookList = bookService.selectAllBook();
        System.out.println(bookList);

    }
    @Test
    void conditionsSelect() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Book> bookList = bookService.selectConditions("0");
        System.out.println(bookList);

    }

    @Test
    void selectBookObject() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        Book book = bookService.selectBookObject("124");
        System.out.println(book);

    }
    @Test
    void selectBookLike() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List bookList = bookService.selectBookLike("root");
        System.out.println(bookList);

    }

    @Test
    void selectBookPage() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List bookList = bookService.selectBookPage(0,2);
        System.out.println(bookList);

    }

    @Test
    void batchAddBook() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        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.batchAddBook(batchArgs);

    }
    @Test
    void batchUpdateBook() {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {
    
    "java0909","a3","3"};
        Object[] o2 = {
    
    "c++1010","b4","4"};
        Object[] o3 = {
    
    "MySQL1111","c5","5"};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchUpdateBook(batchArgs);

    }

    @Test
    void batchDeleteBook() {
    
    
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        BookService bookService = context.getBean("bookService", BookService.class);
        List<Object[]> batchArgs = new ArrayList<>();
        Object[] o1 = {
    
    "3"};
        Object[] o2 = {
    
    "4"};
        Object[] o3 = {
    
    "5"};
        batchArgs.add(o1);
        batchArgs.add(o2);
        batchArgs.add(o3);
        bookService.batchDeleteBook(batchArgs);

    }

6.1事务管理

1、什么事务
(1)事务是数据库操作最基本单元,逻辑上一组操作,要么都成功,如果有一个失败所有操作都失败(2)典型场景:银行转账.
lucy 转账 100 元 给 mary
lucy 少 100,mary 多 100
2、事务四个特性(ACID)
2.1原子性: 原子性是指事务是一个不可再分割的工作单位,事务中的操作要么都发生,要么都不发生。

2.2一致性:一致性是指在事务开始之前和事务结束以后,数据库的完整性约束没有被破坏。这是说数据库事务不能破坏关系数据的完整性以及业务逻辑上的一致性。

2.隔离性:隔离性是指并发的事务是相互隔离的。即一个事务内部的操作及正在操作的数据必须封锁起来,不被企图进行修改的事务看到 。

2.4持久性:持久性是指在事务完成以后,该事务所对数据库所作的更改便持久的保存在数据库之中,并不会被回滚。 即使出现了任何事故比如断电等,事务一旦提交,则持久化保存在数据库中。

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

在这里插入图片描述事务操作(注解声明式事务管理)
1、在 spring 配置文件配置事务管理器

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

<!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
        <property name="url" value="jdbc:mysql://localhost/book_ctiy?serverTimezone=GMT%2B8"> </property>
        <property name="username" value="root"> </property>
        <property name="password" value="2732195202"> </property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"> </property>
    </bean>

<!--    配置 JdbcTemplate 对象,注入 DataSource -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"  >
<!-- 将数据库连接池的信息注入到 dataSource 对象中-->
    <property name="dataSource" ref="dataSource"> </property>
    </bean>

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

</beans>

2、在 spring 配置文件,开启事务注解

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

(2)开启事务注解
在这里插入图片描述
3、在 service 类上面(或者 service 类里面方法上面)添加事务注解

@Service
public class UserDaoService {
    
    

    @Autowired
    private UserDao userDao;
    @Transactional //开启事务管理 可以添加到类上 可以添加到方法上 添加到类上就是类中所有的方法都开启事务管理
    public void accountMoney() {
    
    

        // 1.开启事务操作

           //admin 少100  root多100  2.事务开启事务
           //减钱
           userDao.reduceMoney();
           //模拟异常
           int i = 20/0;
           //加钱
           userDao.addMoney();
           //3.没有异常 提交事务

           //4.出现异常 事务回滚

    }


}

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

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

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

在这里插入图片描述
4.2、propagation:事务传播行为
(1)多事务方法直接进行调用,这个过程中事务 是如何进行管理的

在这里插入图片描述
事务的传播行为可以由传播属性指定。Spring定义了7种类传播行为。
在这里插入图片描述
示例:
在这里插入图片描述
4.3、ioslation:事务隔离级别
(1)事务有特性成为隔离性,多事务操作之间不会产生影响。不考虑隔离性产生很多问题
(2)有三个读问题:脏读、不可重复读、虚(幻)读
(3)脏读:一个未提交事务读取到另一个未提交事务的数据

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

在这里插入图片描述(5)虚读:一个未提交事务读取到另一提交事务添加数据

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

在这里插入图片描述
示例:
在这里插入图片描述
4.4、timeout:超时时间
(1)事务需要在一定时间内进行提交,如果不提交进行回滚
(2)默认值是 -1 ,设置时间以秒单位进行计算

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

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

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

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

1、在 spring 配置文件中进行配置

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

<!--配置数据库连接池-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="clone">
        <property name="url" value="jdbc:mysql://localhost/book_ctiy?serverTimezone=GMT%2B8"> </property>
        <property name="username" value="root"> </property>
        <property name="password" value="2732195202"> </property>
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"> </property>
    </bean>

<!--    配置 JdbcTemplate 对象,注入 DataSource -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"  >
<!-- 将数据库连接池的信息注入到 dataSource 对象中-->
    <property name="dataSource" ref="dataSource"> </property>
    </bean>

<!-- spring配置文件配置事务管理器   -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据源-->
        <property name="dataSource" ref="dataSource"> </property>
    </bean>
    <!--2 配置通知-->
    <tx:advice id="txadvice">
        <!--配置事务参数-->
        <tx:attributes>
            <!--指定哪种规则的方法上面添加事务-->
            <tx:method name="accountMoney" propagation="REQUIRED"/>
            <!--<tx:method name="account*"/>-->
        </tx:attributes>
    </tx:advice>

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

</beans>

第一步 配置事务管理器
在这里插入图片描述

第二步 配置通知
在这里插入图片描述

第三步 配置切入点和切面
在这里插入图片描述service 方法上的注解就可以去掉了
在这里插入图片描述测试:

    @Test
    void accountMoneyXml() {
    
    

        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserDaoService userDaoService = context.getBean("userDaoService", UserDaoService.class);
        userDaoService.accountMoney();

    }

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

不需要配置文件 用配置类取代配置文件
1、创建配置类,使用配置类替代 xml 配置文件

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.maven.spring") //组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
    
    

    //创建数据库连接池
    @Bean
    public DruidDataSource getDruidDataSource() {
    
    
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost/book_ctiy?serverTimezone=GMT%2B8");
        dataSource.setUsername("root");
        dataSource.setPassword("2732195202");
        return dataSource;
    }

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

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

2.在方法上开启事务注解
在这里插入图片描述
测试:

//纯注解事务管理
    @Test
    void accountMoneyAnnotations() {
    
    

        ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
        UserDaoService userDaoService = context.getBean("userDaoService", UserDaoService.class);
        userDaoService.accountMoney();

    }

7.Spring5 框架新功能

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

第一步 引入 jar 包

		<!--Spring5.x 日志封装依赖 -->

		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-core -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>2.11.1</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>2.11.1</version>
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.7.30</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-slf4j-impl</artifactId>
			<version>2.11.1</version>
			<scope>test</scope>
		</dependency>

第二步 创建 log4j2.xml 配置文件

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

3、Spring5 框架核心容器支持@Nullable 注解
(1)@Nullable 注解可以使用在方法上面,属性上面,参数上面,表示方法返回可以为空,属性值可以
为空,参数值可以为空
(2)注解用在方法上面,方法返回值可以为空

在这里插入图片描述
(3)注解使用在方法参数里面,方法参数可以为空

在这里插入图片描述

(4)注解使用在属性上面,属性值可以为空
在这里插入图片描述

8.总结

1、Spring 框架概述
(1)轻量级开源 JavaEE 框架,为了解决企业复杂性,两个核心组成:IOC 和 AOP
(2)Spring5.2.6 版本
2、IOC 容器
(1)IOC 底层原理(工厂、反射等)
(2)IOC 接口(BeanFactory)
(3)IOC 操作 Bean 管理(基于 xml)
(4)IOC 操作 Bean 管理(基于注解)
3、Aop
(1)AOP 底层原理:动态代理,有接口(JDK 动态代理),没有接口(CGLIB 动态代理)
(2)术语:切入点、增强(通知)、切面
(3)基于 AspectJ 实现 AOP 操作
4、JdbcTemplate
(1)使用 JdbcTemplate 实现数据库 curd 操作
(2)使用 JdbcTemplate 实现数据库批量操作
5、事务管理
(1)事务概念
(2)重要概念(传播行为和隔离级别)
(3)基于注解实现声明式事务管理
(4)完全注解方式实现声明式事务管理
6、Spring5 新功能
(1)整合日志框架
(2)@Nullable 注解
(3)函数式注册对象
(4)整合 JUnit5 单元测试框架
(5)SpringWebflux 使用(后面完善)

猜你喜欢

转载自blog.csdn.net/m0_46188681/article/details/112135180