Spring5

1 Spring的概念

1.1 Spring框架的概述

  • Spring是轻量级的开源的JavaEE框架。

  • Spring框架可以解决企业应用开发的复杂性。

  • Spring框架有两个核心部分:IOC和AOP。

    • IOC:控制反转,把创建对象的过程交给Spring进行管理。
    • AOP:面向切面,在不修改源代码的情况下进行功能的增强。
  • Spring框架的特点:

    • 方便解耦,简化开发。
    • AOP编程的支持。
    • 方便程序的测试。
    • 方便集成各种优秀框架。
    • 降低JavaEE API的使用难度。
    • 声明式事务的支持。
    • Spring框架是Java源码学习的经典范例。

1.2 Spring框架的入门案例

1.2.1 导入Spring5相关jar包的Maven坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>

1.2.2 创建普通类

  • User.java
package com.sunxiaping;

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

1.2.3 创建Spring的配置文件,在配置文件中配置要创建的对象

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

    <bean id="user" class="com.sunxiaping.User"></bean>
    
</beans>

1.2.4 测试

  • 示例:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserTest {
    public static void main(String[] args) {
        //加载配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //获取配置创建的对象
        User user = context.getBean("user", User.class);
        user.add();
    }
}

2 IOC容器

2.1 概念和原理

2.1.1 什么是IOC?

  • IOC(控制反转),把对象的创建和对象之间调用的过程,交给Spring进行管理。
  • 使用IOC的目的:为了降低耦合度。

2.1.2 IOC的底层原理

  • xml解析、工厂设计模式、反射。

2.2 IOC接口(BeanFactory)

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

  • Spring提供IOC容器实现的两种方式:

    • BeanFactory:

      • IOC容器最基本的实现方式,是Spring内部的使用接口,不提供开发人员进行使用。
      • 加载配置文件的时候不会去创建对象,而是在获取对象(或使用对象)的时候才去创建对象。
    • ApplicationContext:

      • BeanFactory接口的子接口,提供更多更强大的功能,一般是由开发人员进行使用的。
      • 加载配置的文件的时候就会立即创建对象。
      • ApplicationContext接口的实现类。

      Spring5

2.3 IOC操作Bean管理

2.3.1 什么是Bean管理?

  • Bean管理指的是如下的两个操作:
    • Spring创建对象。
    • Spring注入属性。

2.3.2 Bean管理的操作有两种实现方法

  • 基于XML配置文件方式实现。
  • 基于注解方式实现。

2.3.3 基于XML方式进行Bean管理的操作

2.3.3.1 基于XML方式创建对象

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

    <!--
        在Spring配置文件中,使用bean标签,标签中添加对应的属性即可,就可以实现对象的创建。
		在Bean标签中有很多属性,如下是一些常用的属性:
 			- id属性:唯一标识。
			- class属性:类的全路径。 
		创建对象的时候,默认是调用的是无参构造方法。
    -->
    <bean id="user" class="com.sunxiaping.User"></bean>

</beans>

2.2.3.2 基于XML方式注入属性

  • DI:依赖注入,就是注入属性。
2.2.3.2.1 创建对象和使用Setter方法进行注入
  • 示例:通过Setter方法进行注入
  • Book.java
package com.sunxiaping;

public class Book {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="book" class="com.sunxiaping.Book">
       <!--
			使用property完成属性注入
				name:类里面属性名称
				value:向属性中注入的值
		-->
       <property name="name" value="红楼梦"/>
   </bean>

</beans>
  • 测试
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book.getName() = " + book.getName());
    }

}
2.2.3.2.2 有参构造注入属性
  • 示例:使用有参构造方法进行注入
  • Book.java
package com.sunxiaping;

public class Book {

    private String name;

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean id="book" class="com.sunxiaping.Book" >
       <constructor-arg name="name" value="西游记"/>
   </bean>

</beans>
  • 测试
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book.getName() = " + book.getName());
    }
}
2.2.3.2.3 p名称空间注入
  • 示例:p名称空间注入,可以简化Setter方法注入
  • Book.java
package com.sunxiaping;

public class Book {

    private String name;

    private Double price;

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="book" class="com.sunxiaping.Book" p:name="红楼梦" p:price="20">
    </bean>

</beans>
  • 测试
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book = " + book);
    }
}
2.2.3.2.4 注入null和特殊字符
  • 示例:注入null和特殊字符
  • Book.java
package com.sunxiaping;

public class Book {

    private String name;

    private Double price;

    private String address;

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", price=" + price +
                ", address='" + address + '\'' +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="book" class="com.sunxiaping.Book">
        <!--
            null值
        -->
        <property name="name">
            <null></null>
        </property>

        <!-- 属性值包含特殊字符 -->
        <property name="address">
            <value><![CDATA[<<江苏>>]]]></value>
        </property>

    </bean>

</beans>
  • 测试
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        System.out.println("book = " + book);
    }
}
2.2.3.2.5 注入属性-外部Bean
  • 示例:注入属性-外部Bean
  • UserDao.java
package com.sunxiaping.dao;

public interface UserDao {

    public void update();

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;

public class UserDaoImpl implements UserDao {

    @Override
    public void update() {
        System.out.println("dao update....");
    }
}
  • UserService.java
package com.sunxiaping.service;

import com.sunxiaping.dao.UserDao;

public class UserService {

    private UserDao userDao;

    public UserDao getUserDao() {
        return userDao;
    }

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

    public void update(){
        System.out.println("service update...");
        userDao.update();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="userDao" class="com.sunxiaping.dao.impl.UserDaoImpl"></bean>

    <bean id="userService" class="com.sunxiaping.service.UserService">
        <property name="userDao" ref="userDao"></property>
    </bean>

</beans>
  • 测试
package com.sunxiaping;

import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class UserServiceTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.update();
    }
}
2.2.3.2.6 注入属性-内部Bean
  • 示例:注入属性-内部Bean(以部门和员工为例)
  • Dept.java
package com.sunxiaping;

import java.io.Serializable;

/**
 * 部门
 */
public class Dept implements Serializable {

    /**
     * 部门名称
     */
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Dept{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Employee.java
package com.sunxiaping;

import java.io.Serializable;

/**
 * 员工
 */
public class Employee implements Serializable {

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String gender;

    /**
     * 一个员工属于一个部门
     */
    private Dept dept;

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Dept getDept() {
        return dept;
    }

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

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="emp" class="com.sunxiaping.Employee">
        <property name="name" value="张三"/>
        <property name="gender" value="男"/>
        <!--
            设置内部Bean
        -->
        <property name="dept">
            <bean id="dept" class="com.sunxiaping.Dept">
                <property name="name" value="开发部"/>
            </bean>
        </property>
    </bean>
    
</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp", Employee.class);
        System.out.println("employee = " + employee);
    }
}
2.2.3.2.7 注入属性-级联赋值
  • 示例:注入属性-级联赋值
  • Dept.java
package com.sunxiaping;

import java.io.Serializable;

/**
 * 部门
 */
public class Dept implements Serializable {

    /**
     * 部门名称
     */
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Dept{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Employee.java
package com.sunxiaping;

import java.io.Serializable;

/**
 * 员工
 */
public class Employee implements Serializable {

    /**
     * 姓名
     */
    private String name;

    /**
     * 性别
     */
    private String gender;

    /**
     * 一个员工属于一个部门
     */
    private Dept dept = new Dept();

    public String getName() {
        return name;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Dept getDept() {
        return dept;
    }

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

    @Override
    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", gender='" + gender + '\'' +
                ", dept=" + dept +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="emp" class="com.sunxiaping.Employee">
        <property name="name" value="张三"/>
        <property name="gender" value="男"/>
        <property name="dept.name" value="测试部"/>
    </bean>
    
</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp", Employee.class);
        System.out.println("employee = " + employee);
    }
}
2.2.3.2.8 注入集合类型属性
  • 示例:注入数组类型属性、注入List类型属性、注入Set类型属性、注入Map类型属性

  • Student.java

package com.sunxiaping;

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

public class Student {

    private String[] courses;

    private List<String> list;

    private Map<String, String> map;

    private Set<String> set;

    public String[] getCourses() {
        return courses;
    }

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

    public List<String> getList() {
        return list;
    }

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

    public Map<String, String> getMap() {
        return map;
    }

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

    public Set<String> getSet() {
        return set;
    }

    public void setSet(Set<String> set) {
        this.set = set;
    }

    @Override
    public String toString() {
        return "Student{" +
                "courses=" + Arrays.toString(courses) +
                ", list=" + list +
                ", map=" + map +
                ", set=" + set +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.sunxiaping.Student">
        <property name="courses">
            <array>
                <value>Java课程</value>
                <value>Linux课程</value>
                <value>前端课程</value>
            </array>
        </property>
        <property name="list">
            <list>
                <value>list1</value>
                <value>list2</value>
                <value>list3</value>
            </list>
        </property>
        <property name="set">
            <set>
                <value>set1</value>
                <value>set2</value>
                <value>set3</value>
            </set>
        </property>
        <property name="map">
            <map>
                <entry key="map-key1" value="map-value1"/>
                <entry key="map-key2" value="map-value2"/>
                <entry key="map-key2" value="map-value2"/>
            </map>
        </property>

    </bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StudentTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student = context.getBean("student", Student.class);

        System.out.println("student = " + student);
    }
}
2.2.3.2.9 注入集合对象类型
  • 示例:注入集合对象类型
  • Course.java
package com.sunxiaping;

public class Course {

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Course{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • Student.java
package com.sunxiaping;

import java.util.List;

public class Student {

    private List<Course> courseList ;

    public List<Course> getCourseList() {
        return courseList;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "courseList=" + courseList +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="student" class="com.sunxiaping.Student">
        <property name="courseList">
            <list>
                <ref bean="java"></ref>
                <ref bean="php"></ref>
            </list>
        </property>
    </bean>

    <bean id="java" class="com.sunxiaping.Course">
        <property name="name" value="java"/>
    </bean>

    <bean id="php" class="com.sunxiaping.Course">
        <property name="name" value="php"/>
    </bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class StudentTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Student student = context.getBean("student", Student.class);

        System.out.println("student = " + student);
    }
}
2.2.3.2.10 工厂Bean
  • 工厂Bean的步骤:

  • ①创建类,让这个类作为工厂Bean,实现接口FactoryBean。

  • ②实现接口里面的方法,在方法的定义中定义返回的Bean类型。

  • 示例:工厂Bean

  • Demo.java

package com.sunxiaping;

public class Demo {

    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Demo{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • FactoryBeanDemo.java
package com.sunxiaping;

import org.springframework.beans.factory.FactoryBean;

public class FactoryBeanDemo implements FactoryBean<Demo> {

    /**
     * 定义返回Bean
     *
     * @return
     * @throws Exception
     */
    @Override
    public Demo getObject() throws Exception {
        Demo demo = new Demo();
        demo.setName("这是一个Demo");
        return demo;
    }

    @Override
    public Class<?> getObjectType() {
        return Demo.class;
    }

    @Override
    public boolean isSingleton() {
        return false;
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

      <bean id="demo" class="com.sunxiaping.FactoryBeanDemo"></bean>
    
</beans>
  • 示例:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class DemoTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        Demo demo = context.getBean("demo", Demo.class);

        System.out.println("demo = " + demo);
    }
}

2.2.3.3 Bean的作用域

  • 在Spring中,可以设置创建Bean实例是单实例还是多实例。

  • 在Spring中,默认情况下,Bean是单实例对象。

  • 示例:单实例Bean

  • Book.java

package com.sunxiaping;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="book" class="com.sunxiaping.Book"></bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);

        System.out.println(book == book2);//true

    }
}
  • 示例:多实例Bean
  • Book.java
package com.sunxiaping;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--
            默认情况下,scope的值是singleton,表示单实例Bean。
            如果scope的值是prototype,则表示多实例Bean。
     --> 
     <bean id="book" class="com.sunxiaping.Book" scope="prototype"></bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Book book = context.getBean("book", Book.class);
        Book book2 = context.getBean("book", Book.class);

        System.out.println(book == book2);//false
    }
}

singleton和prototype的区别?

①singleton是单实例,prototype是多实例。

②设置scope的值是singleton的时候,加载Spring的配置文件的时候就会创建单实例对象。设置scope的值是prototype的时候,不是在加载Spring的配置文件的时候就会对象,而是在调用getBean()方法的时候创建对象。

2.2.3.4 Bean的生命周期

  • 生命周期:从对象的创建到对象的销毁的过程。

  • Bean生命周期:

    • ①通过构造器创建Bean实例(默认是通过无参构造器)
    • ②为Bean的属性设置值和对其他Bean的引用(调用Setter方法)
    • 调用Bean的初始化的方法(需要进行配置初始化的方法)。
    • ④使用Bean对象。
    • ⑤当容器的关闭的时候,会调用Bean的销毁方法(需要进行配置销毁的方法)。
  • 示例:

  • Book.java

package com.sunxiaping;

public class Book {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        System.out.println("②调用setter方法设置属性值");
        this.name = name;
    }

    public Book() {
        System.out.println("①无参构造方法");
    }

    public void init() {
        System.out.println("③这是初始化方法...");
    }

    public void destroy() {
        System.out.println("⑤这是销毁的方法...");
    }


    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--
            init-method配置初始化方法
            destroy-method配置销毁方法
     -->
     <bean id="book" class="com.sunxiaping.Book" init-method="init" destroy-method="destroy">
          <property name="name" value="哈哈"/>
     </bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        //④调用Bean对象
        Book book = context.getBean("book", Book.class);
        System.out.println("④调用Bean对象" + book);
        //手动调用让容器关闭
        context.close();

    }
}
  • 后置处理器:会在Bean的初始化前后处理,将Bean传递给Bean的后置处理器方法

  • 添加后置处理器的Bean的生命周期:

    • ①通过构造器创建Bean实例(默认是通过无参构造器)
    • ②为Bean的属性设置值和对其他Bean的引用(调用Setter方法)
    • ③将Bean实例传递给Bean的后置处理器的方法。
    • ④调用Bean的初始化的方法(需要进行配置初始化的方法)。
    • ⑤将Bean实例传递给Bean的后置处理器的方法。
    • ⑥使用Bean对象。
    • ⑦当容器的关闭的时候,会调用Bean的销毁方法(需要进行配置销毁的方法)。
  • 示例:只需要让类实现BeanPostProcessor,并重写其中的方法即可。

  • Book.java

package com.sunxiaping;

public class Book  {
    
    public void init(){
        System.out.println("Book初始化...");
    }
}
  • Demo.java
package com.sunxiaping;

public class Demo {

    public void init(){
        System.out.println("Demo初始化...");
    }
}
  • MyBeanPostProcessor.java
package com.sunxiaping;

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

public class MyBeanPostProcessor 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;
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

     <bean id="book" class="com.sunxiaping.Book" init-method="init" ></bean>

     <bean id="demo" class="com.sunxiaping.Demo" init-method="init"></bean>

     <!--配置后置处理器-->
     <bean id="myBeanPostProcessor" class="com.sunxiaping.MyBeanPostProcessor"></bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BookTest {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

    }
}

2.3.3.5 自动装配

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

  • 示例:根据属性名称自动注入

  • Dept.java

package com.sunxiaping;

import java.io.Serializable;

public class Dept implements Serializable {

    @Override
    public String toString() {
        return "Dept{}";
    }
}
  • Employee.java
package com.sunxiaping;

import java.io.Serializable;

public class Employee implements Serializable {

    private Dept dept;

    public Dept getDept() {
        return dept;
    }

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

    @Override
    public String toString() {
        return "Employee{" +
                "dept=" + dept +
                '}';
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

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

     <!--
          实现自动装配
          bean标签中有属性autowire:
               - 属性值 byName,根据属性名注入,注入Bean的id值要和类属性一致
               - 属性值 byType,根据属性类型注入,注入Bean的类型要和类属性类型一致
     -->
     <bean id="emp" class="com.sunxiaping.Employee" autowire="byName"></bean>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeTest {
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        Employee employee = context.getBean("emp",Employee.class);

        System.out.println("employee = " + employee);
    }
}

2.3.3.6 外部属性文件

  • 示例:通过引入外部属性文件配置数据库连接池
  • 导入数据库连接池的Maven坐标
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
  • db.properties
jdbc.url=jdgc:mysql://localhost:3306/db01
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.user=root
jdbc,password=123456
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

</beans>

2.3.4 基于注解方式进行Bean管理的操作

2.3.4.1 什么是注解?

  • 注解是代码的一种特殊标记,注解可以作用在类、方法和属性上面。
  • 语法:
@注解名称(属性名称=属性值,属性名称=属性值...)
  • 使用注解的目的,是简化XML的配置。

2.3.4.2 Spring针对Bean管理中创建对象提供的注解

  • @Component
  • @Service
  • @Controller
  • @Repository

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

2.3.4.3 基于注解方式创建对象

  • 示例:
  • UserService.java
package com.sunxiaping.service;

import org.springframework.stereotype.Service;

/**
 * 在注解里面value属性值可以省略不写,默认值是类名首字母小写
 */
@Service(value = "userService")
public class UserService {
    
    public void add() {
        System.out.println("UserService  ...");
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

</beans>
  • 测试:
package com.sunxiaping;

import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }
}

2.3.4.4 组件扫描配置

  • 示例:applicaitonContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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">

    <!--
        默认情况下,如果不加use-default-filters="false",则表示使用默认的filter,而默认的filter是扫描指定包下的所有组件
        如果加了use-default-filters="false",则表示不使用默认的filter,自已配置filter
            context:include-filter,设置扫描那些内容
    -->
    <context:component-scan base-package="com.sunxiaping" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    

</beans>
  • 示例:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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:exclude-filter 设置不扫描那些内容
    -->
    <context:component-scan base-package="com.sunxiaping">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

</beans>

2.3.4.5 基于注解注入属性

  • Spring注入属性提供的注解:

    • @Autowired:根据属性类型进行自动装配。
    • @Qualifier:根据属性名称进入注入。
    • @Resource:可以根据类型注入,也可以根据名称注入。
    • @Value:注入普通类型属性。
  • 示例:@Autowired注解的使用

  • UserDao.java

package com.sunxiaping.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package com.sunxiaping.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.UserDao;
import com.sunxiaping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    //@Autowired按照类型注入
    @Autowired
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

</beans>
  • 测试:
package com.sunxiaping;

import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }
    
}
  • 示例:@Qualifier注解的使用
  • UserDao.java
package com.sunxiaping.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package com.sunxiaping.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.UserDao;
import com.sunxiaping.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    //@Qualifier注解按照属性名称注入,其中属性value的值是要注入Bean的id
    //@Qualifier注解要和@Autowired配合使用
    @Autowired
    @Qualifier(value = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

</beans>
  • 测试:
package com.sunxiaping;

import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}
  • 示例:@Resource注解的使用
  • UserDao.java
package com.sunxiaping.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package com.sunxiaping.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.UserDao;
import com.sunxiaping.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    //@Resource注解如果不写name属性,那么就是按照类型注入
    //@Resource注解如果写name属性,那么就是按照名称注入
    @Resource(name = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

</beans>
  • 测试:
package com.sunxiaping;

import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}

2.3.4.6 完全注解开发

  • 开发步骤:

    • ①创建一个配置类,用来替代applicationContext.xml文件。
    • ②测试的时候,使用的是AnnotationConfigApplicationContext,而不是ClassPathXmlApplicationContext。
  • 示例:

  • UserDao.java

package com.sunxiaping.dao;

public interface UserDao {

    void add();

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;
import org.springframework.stereotype.Repository;

@Repository
public class UserDaoImpl implements UserDao {
    @Override
    public void add() {
        System.out.println("UserDaoImpl。。。add。。。");
    }
}
  • UserService.java
package com.sunxiaping.service;

public interface UserService {

    void add();

}
  • UserServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.UserDao;
import com.sunxiaping.service.UserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {

    //@Resource注解如果不写name属性,那么就是按照类型注入
    //@Resource注解如果写name属性,那么就是按照名称注入
    @Resource(name = "userDaoImpl")
    private UserDao userDao;

    @Override
    public void add() {
        System.out.println("UserServiceImpl...add...");
        userDao.add();
    }
}
  • SpringConfing.java
package com.sunxiaping.config;

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

/**
 * 配置类,相当于applicationContext.xml
 */
@Configuration
@ComponentScan(basePackages = "com.sunxiaping")
public class SpringConfig {

}
  • 测试:
package com.sunxiaping;

import com.sunxiaping.config.SpringConfig;
import com.sunxiaping.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Spring5Test {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        UserService userService = context.getBean("userServiceImpl", UserService.class);
        userService.add();
    }

}

3 AOP

3.1 概念

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

3.2 AOP底层原理

  • 使用JDK的动态代理。

  • 使用CGLIB的动态代理。

  • 示例:使用JDK的动态代理

  • UserDao.java

package com.sunxiaping.dao;

public interface UserDao {

    int add(int a, int b);

    String update(String id);

}
  • UserDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.UserDao;

public class UserDaoImpl implements UserDao {
    @Override
    public int add(int a, int b) {

        System.out.println("add...执行了");

        return a + b;
    }

    @Override
    public String update(String id) {

        System.out.println("update...执行了");

        return id;
    }
}
  • 测试:
package com.sunxiaping;

import com.sunxiaping.dao.UserDao;
import com.sunxiaping.dao.impl.UserDaoImpl;

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

public class SpringTest {
    public static void main(String[] args) {

        UserDao userDao = new UserDaoImpl();

        UserDao proxy = (UserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("在" + method.getName() + "之前执行");
                Object result = method.invoke(userDao, args);
                System.out.println("在" + method.getName() + "之后执行");
                return result;
            }
        });

        int result = proxy.add(1, 2);
        System.out.println("result = " + result);

        String id = proxy.update("1");
        System.out.println("id = " + id);

    }
}

3.3 AOP术语

  • 连接点:类里面那些方法可以被增强,这些方法称为连接点。
  • 切入点:实际被真正增强的方法,称为切入点。
  • 通知(增强):实际增强的逻辑部分,称为通知(增强)。
  • 通知的类型:
    • 前置通知。
    • 后置通知。
    • 环绕通知。
    • 异常通知。
    • 最终通知。
  • 切面:把通知应用到切入点的过程。

3.4 AOP的准备

  • 在Spring框架一般基于AspectJ(AspectJ不是Spring的部分,是一个独立的AOP框架,一般把AspectJ和Spring框架一起使用,进行AOP的操作)来实现AOP操作。

  • 导入相关jar包的Maven坐标:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
  • 切入点表达式:

    • 作用:对哪个类里面的哪个方法进行增强。
    • 语法:
    execution([权限修饰符][返回类型][类全路径][方法名称([参数列表])])
    
    • 例子:

      • 对com.sunxiaping.dao.BookDao类中add方法进行增强:
      execution(* com.sunxiaping.dao.BookDao.add(..))
      
      • 对com.sunxiaping.dao.BookDao类中的所有方法进行增强:
      execution(* com.sunxiaping.dao.BookDao.*(..))
      

3.5 AspectJ注解形式应用示例

  • 示例:
  • 被增强的类User.java
package com.sunxiaping;

import org.springframework.stereotype.Component;

/**
 * 被增强类
 */
@Component
public class User {

    public void add(){
        System.out.println("add ...");
    }
}
  • 增强的类,即代理类UserAspect.java
package com.sunxiaping;

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

/**
 * 增强的类
 */
@Component
@Aspect //生成代理对象
@Order(1) //在多个增强类对同一个方法进行增强,设置增强类的优先级,@Order中的value属性值越小优先级越高
public class UserAspect {
    /**
     * 切入点表达式
     */
    @Pointcut("execution(* com.sunxiaping.User.add(..))")
    public void pointcut() {
    }

    /**
     * 前置通知
     */
    @Before(value = "pointcut()")
    public void beforeAdd() {
        System.out.println("before add ...");
    }

    /**
     * 后置通知
     */
    @AfterReturning(value = "pointcut()", returning = "obj")
    public void afterReturningAdd(Object obj) {
        System.out.println("afterReturning add ..." + obj);
    }


    /**
     * 环绕通知
     */
    @Around(value = "pointcut()")
    public void aroundAdd(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前");
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后");
    }

    /**
     * 异常通知
     */
    @AfterThrowing(value = "pointcut()", throwing = "ex")
    public void afterThrowingAdd(Exception ex) {
        System.out.println("afterThrowing add ..." + ex);
    }

    /**
     * 最终通知
     */
    @After(value = "pointcut()")
    public void afterAdd() {
        System.out.println("after add ...");
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>


    <!-- 开启aspectj生成代理对象 -->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        User user = context.getBean(User.class);

        user.add();
    }
}

3.6 完全使用注解开发AspectJ

  • 示例:
  • 被增强的类User.java
package com.sunxiaping;

import org.springframework.stereotype.Component;

/**
 * 被增强类
 */
@Component
public class User {

    public void add(){
        System.out.println("add ...");
    }
}
  • 增强的类,即代理类UserAspect.java
package com.sunxiaping;

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

/**
 * 增强的类
 */
@Component
@Aspect //生成代理对象
@Order(1) //在多个增强类对同一个方法进行增强,设置增强类的优先级,@Order中的value属性值越小优先级越高
public class UserAspect {
    /**
     * 切入点表达式
     */
    @Pointcut("execution(* com.sunxiaping.User.add(..))")
    public void pointcut() {
    }

    /**
     * 前置通知
     */
    @Before(value = "pointcut()")
    public void beforeAdd() {
        System.out.println("before add ...");
    }

    /**
     * 后置通知
     */
    @AfterReturning(value = "pointcut()", returning = "obj")
    public void afterReturningAdd(Object obj) {
        System.out.println("afterReturning add ..." + obj);
    }


    /**
     * 环绕通知
     */
    @Around(value = "pointcut()")
    public void aroundAdd(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕之前");
        proceedingJoinPoint.proceed();
        System.out.println("环绕之后");
    }

    /**
     * 异常通知
     */
    @AfterThrowing(value = "pointcut()", throwing = "ex")
    public void afterThrowingAdd(Exception ex) {
        System.out.println("afterThrowing add ..." + ex);
    }

    /**
     * 最终通知
     */
    @After(value = "pointcut()")
    public void afterAdd() {
        System.out.println("after add ...");
    }
}
  • SpringConfig.java
package com.sunxiaping;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@EnableAspectJAutoProxy(proxyTargetClass = true)
@ComponentScan(basePackages = "com.sunxiaping")
@Configurable
public class SpringConfig {
}
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringTest {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);

        User user = context.getBean(User.class);

        user.add();
    }

}

3.7 XML形式应用示例

  • 被增强的类User.java
package com.sunxiaping;

/**
 * 被增强类
 */
public class User {

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

}
  • 增强的类,即代理类UserAspect.java
package com.sunxiaping;

/**
 * 增强的类
 */
public class UserAspect {

    /**
     * 前置通知
     */
    public void beforeAdd() {
        System.out.println("before add ...");
    }
}
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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="user" class="com.sunxiaping.User"></bean>

    <bean id="userAspect" class="com.sunxiaping.UserAspect"></bean>

    <!-- 配置aop -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.sunxiaping.User.add(..)))"/>
        <!-- 配置切面 -->
        <aop:aspect ref="userAspect">
            <!-- 配置增强作用在具体的方法上 -->
            <aop:before method="beforeAdd" pointcut-ref="pointcut"></aop:before>
        </aop:aspect>
    </aop:config>

</beans>
  • 测试:
package com.sunxiaping;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        User user = context.getBean(User.class);

        user.add();
    }
}

4 JdbcTemplate

4.1 概念

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

4.2 准备工作

  • 导入相关jar包的Maven坐标:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>
  • sql语句:
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book`  (
  `id` bigint(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
  `price` double NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
  • Book.java
package com.sunxiaping.domain;

import java.io.Serializable;

/**
 * 图书
 */
public class Book implements Serializable {

    /**
     * 主键
     */
    private Long id;

    /**
     * 书名
     */
    private String name;

    /**
     * 价格
     */
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                '}';
    }
}
  • db.properties
jdbc.url=jdbc:mysql://192.168.1.107:33060/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=123456
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

    <!-- 导入数据库连接信息 -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

</beans>

4.3 JdbcTemplate的CRUD

  • BookDao.java
package com.sunxiaping.dao;

import com.sunxiaping.domain.Book;

import java.util.List;

public interface BookDao {
    /**
     * 新增
     *
     * @param book
     */
    void add(Book book);

    /**
     * 更新
     *
     * @param book
     */
    void update(Book book);

    /**
     * 删除
     *
     * @param id
     */
    void delete(Long id);

    /**
     * 查询个数
     *
     * @return
     */
    Long count();

    /**
     * 查询所有信息
     *
     * @return
     */
    List<Book> findAll();

    /**
     * 根据主键查询信息
     *
     * @param id
     * @return
     */
    Book findOne(Long id);

}
  • BookDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.BookDao;
import com.sunxiaping.domain.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class BookDaoImpl implements BookDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(Book book) {
        jdbcTemplate.update(" insert into book (name,price) values (?,?) ", book.getName(), book.getPrice());
    }

    @Override
    public void update(Book book) {
        jdbcTemplate.update(" update book set name =?,price =? where id = ? ", book.getName(), book.getPrice(), book.getId());
    }

    @Override
    public void delete(Long id) {
        jdbcTemplate.update(" delete from book where id =? ", id);
    }

    @Override
    public Long count() {
        return jdbcTemplate.queryForObject(" select count(*) from book ", Long.class);
    }

    @Override
    public List<Book> findAll() {
        return jdbcTemplate.query(" select * from book ", new BeanPropertyRowMapper<>(Book.class));
    }

    @Override
    public Book findOne(Long id) {
        return jdbcTemplate.queryForObject(" select * from book where id = ? ", new BeanPropertyRowMapper<>(Book.class), id);
    }
}
  • BookService.java
package com.sunxiaping.service;

import com.sunxiaping.domain.Book;

import java.util.List;

public interface BookService {

    /**
     * 新增图书
     *
     * @param book
     */
    void addBook(Book book);

    /**
     * 更新图书
     *
     * @param book
     */
    void updateBook(Book book);


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

    /**
     * 查询数据库中有多少本书
     *
     * @return
     */
    Long count();


    /**
     * 查询图书信息
     *
     * @param id
     * @return
     */
    Book view(Long id);

    /**
     * 查询所有图书信息
     *
     * @return
     */
    List<Book> findAllBookList();


}
  • BookServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.BookDao;
import com.sunxiaping.domain.Book;
import com.sunxiaping.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public void addBook(Book book) {
        bookDao.add(book);
    }

    @Override
    public void updateBook(Book book) {
        bookDao.update(book);
    }

    @Override
    public void deleteBook(Long id) {
        bookDao.delete(id);
    }

    @Override
    public Long count() {
        return bookDao.count();
    }

    @Override
    public Book view(Long id) {
        return bookDao.findOne(id);
    }

    @Override
    public List<Book> findAllBookList() {
        return bookDao.findAll();
    }
}
  • 测试:
package com.sunxiaping;

import com.sunxiaping.domain.Book;
import com.sunxiaping.service.BookService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Spring5Test {
    private ApplicationContext context = null;
    private BookService bookService = null;

    @Before
    public void before() {
        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        bookService = context.getBean(BookService.class);
    }

    @Test
    public void testAdd() {
        Book book = new Book();
        book.setName("西游记");
        book.setPrice(20.5);

        bookService.addBook(book);
    }

    @Test
    public void testUpdate() {
        Book book = new Book();
        book.setId(1L);
        book.setName("西游记");
        book.setPrice(50.0);

        bookService.updateBook(book);
    }

    @Test
    public void testDelete() {
        bookService.deleteBook(1L);
    }

    @Test
    public void testCount() {
        Long count = bookService.count();
        System.out.println("count = " + count);
    }

    @Test
    public void testView(){
        Book book = bookService.view(1L);
        System.out.println("book = " + book);
    }


    @Test
    public void testFindAllBookList(){
        List<Book> allBookList = bookService.findAllBookList();

        System.out.println("allBookList = " + allBookList);
    }   
}

5 事务管理

5.1 概念

  • 事务是数据库操作最基本的单元,逻辑上的一组操作,要么全部成功,要么全部失败。

5.2 事务的特性

  • 原子性
  • 一致性
  • 隔离性
  • 持久性

5.3 准备工作

  • account.sql
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '姓名',
  `money` double NULL DEFAULT NULL COMMENT '账户余额',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `account` VALUES (1, 'lucy', 1000);
INSERT INTO `account` VALUES (2, 'marry', 1000);
  • 导入相关jar包的Maven坐标:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>
  • Account.java
package com.sunxiaping.domain;

/**
 * 账户
 */
public class Account {

    /**
     * 主键
     */
    private Long id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 账户余额
     */
    private Double money;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}
  • db.properties
jdbc.url=jdbc:mysql://192.168.1.107:33060/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=123456
  • applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

    <!-- 导入数据库连接信息 -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

5.4 事务操作介绍

5.4.1 概述

  • 事务添加到JavaEE三层结构中的Service层(业务逻辑层)。

  • 在Spring中进行事务管理操作有两种方式:

    • 编程式事务管理。
    • 声明式事务管理(经常使用)。
  • 声明式事务管理:

    • 基于注解方式(经常使用)。
    • 基于XML配置文件方式。
  • Spring事务管理API

    • Spring提供了一个接口,代表事务管理器,这个接口针对不同的框架提供不同的实现类。

    Spring5

    • @Transaction注解可以添加在类上面,也可以放在方法上面。

      • 如果添加在类上面,这个类里面的所有的方法都添加了事务。
      • 如果添加在方法上面,则这个方法添加了事务。
      • 源码:
      package org.springframework.transaction.annotation;
      
      import java.lang.annotation.Documented;
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Inherited;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      import org.springframework.core.annotation.AliasFor;
      
      @Target({ElementType.TYPE, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Inherited
      @Documented
      public @interface Transactional {
          @AliasFor("transactionManager")
          String value() default "";
      
          @AliasFor("value")
          String transactionManager() default "";
      	//传播行为
          Propagation propagation() default Propagation.REQUIRED;
      	//事务隔离级别
          Isolation isolation() default Isolation.DEFAULT;
      	//超时时间
          int timeout() default -1;
      	//是否只读
          boolean readOnly() default false;
          //回滚
          Class<? extends Throwable>[] rollbackFor() default {};
      
          String[] rollbackForClassName() default {};
          //不回滚
          Class<? extends Throwable>[] noRollbackFor() default {};
      
          String[] noRollbackForClassName() default {};
      }
      
      • propagation:事务的传播行为。

        • 多事务方法(对数据库表数据进行变化的操作)直接进行调用,这个过程中事务是如何进行管理的。
        @Transactional
        public void add(){
            //调用update方法
            update();
        }
        public void update(){}
        
        • 属性:
          • REQUIRED:
            • 如果add方法本身有事务,则调用update方法之后,update使用当前add方法里面的事务。
            • 如果add方法本身没有事务,调用update方法之后,会创建新的事务。
          • REQUIRED_NEW:
            • 使用add方法调用update方法,无论add是否有事务,都会创建新的事务。
      • isolation:事务隔离级别。

        • 多事务操作之间不会产生影响。
        • 如果不考虑隔离性,会产生脏读、不可重复读、虚读。
          • 脏读:一个未提交的事务读到另一个事务未提交的事务(针对update)。
          • 不可重复读:一个未提交的事务读到另一个提交事务的修改数据(针对update),前后多次读取,导致数据内容不一致。
          • 幻读:一个未提交的事务读到了另一个提交事务的添加数据(针对insert),前后多次读取,数据总量不一致。
        • 通过设置事务的隔离级别,可以解决脏读问题。
          • READ UNCOMMITTED:会出现脏读、不可重复读、幻读。
          • READ COMMITTED:会出现不可重复读、幻读。
          • REPEATABLE READ:会出现幻读。
          • SERIALIZABLE:不会出现问题。
      • timeout:超时时间。

        • 事务需要在一定时间内进行提交,如果不提交就进行回滚。

        • 在Spring中,默认值是-1(不回滚),设置时间以秒单位进行计算。

    • readOnly:是否只读。

      • 默认值是false,表示可以查询、添加、修改、删除操作。
        
      • 如果设置readOnly为true,就只能查询。
        
      • rollbackFor:回滚。

        • 设置出现了那些异常进行事务回滚。
      • noRollbackFor:不回滚。

        • 设置那些异常不进行事务回滚。

5.4.2 基于注解方式的声明式事务管理

  • 在Spring的配置文件applicationContext.xml中配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
  • 在Spring的配置文件applicationContext.xml中,开启事务注解
<!-- 开启事务注解 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
  • 完整的applicationContext.xml文件信息
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

    <!-- 导入数据库连接信息 -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

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

    <!-- 开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
  • AccountDao.java
package com.sunxiaping.dao;

import com.sunxiaping.domain.Account;

public interface AccountDao {
    /**
     * 转入
     *
     * @param account
     * @param money
     */
    void addMoney(Account account, Double money);

    /**
     * 转出
     *
     * @param account
     * @param money
     */
    void reduceMoney(Account account, Double money);
}
  • AccountDaoImpl.java
package com.sunxiaping.dao.impl;

import com.sunxiaping.dao.AccountDao;
import com.sunxiaping.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void addMoney(Account account, Double money) {
        jdbcTemplate.update(" update account set money = money + ? where username = ? ", money, account.getName());
    }

    @Override
    public void reduceMoney(Account account, Double money) {
        jdbcTemplate.update(" update account set money = money - ? where username = ? ", money, account.getName());
    }
}
  • AccountService.java
package com.sunxiaping.service;

public interface AccountService {

    /**
     * 转账
     *
     * @param from
     * @param target
     * @param money
     */
    void transfer(String from, String target, Double money);

}
  • AccountServiceImpl.java
package com.sunxiaping.service.impl;

import com.sunxiaping.dao.AccountDao;
import com.sunxiaping.domain.Account;
import com.sunxiaping.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Override
    public void transfer(String from, String target, Double money) {
        Account targetAccount = new Account();
        targetAccount.setName(target);
        accountDao.addMoney(targetAccount, money);

        int i = 100 / 0;

        Account fromAccount = new Account();
        fromAccount.setName(from);
        accountDao.reduceMoney(fromAccount, money);
    }
}
  • 测试:
package com.sunxiaping;

import com.sunxiaping.service.AccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

    private AccountService accountService = null;

    @Before
    public void before(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        accountService = context.getBean(AccountService.class);
    }

    @Test
    public void test(){
        accountService.transfer("lucy","marrry",100.00);
    }
}

5.4.3 基于XML配置文件方式的声明式事务管理

  • 在Spring的配置文件applicationContext.xml中配置事务管理器
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <!-- 注入数据源 -->
    <property name="dataSource" ref="dataSource"></property>
</bean>
  • 在Spring的配置文件applicationContext.xml中配置通知
<!-- 配置通知 -->
<tx:advice id="txAdvice">
    <!-- 配置事务参数 -->
    <tx:attributes>
        <!-- 指定那种规则的方法上面添加事务 -->
        <tx:method name="add*" />
        <tx:method name="update*" />
        <tx:method name="delete*" />
    </tx:attributes>
</tx:advice>
  • 在Spring的配置文件applicationContext.xml中配置切入点和通知
<!-- 配置切入点和切面 -->
<aop:config>
    <!-- 配置切入点 -->
    <aop:pointcut id="pointcut" expression="execution(* com.sunxiaping.service.impl.AccountServiceImpl.*(..))"/>
    <!-- 配置切面 -->
    <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
</aop:config>
  • 完整的applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<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="http://www.springframework.org/schema/beans"
       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.sunxiaping"></context:component-scan>

    <!-- 导入数据库连接信息 -->
    <context:property-placeholder location="db.properties"></context:property-placeholder>

    <!-- 配置数据库连接池 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClass}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="username" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <!-- 配置jdbcTemplate -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <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="add*"/>
            <tx:method name="update*"/>
            <tx:method name="delete*"/>
        </tx:attributes>
    </tx:advice>

    <!-- 配置切入点和切面 -->
    <aop:config>
        <!-- 配置切入点 -->
        <aop:pointcut id="pointcut" expression="execution(* com.sunxiaping.service.impl.AccountServiceImpl.*(..))"/>
        <!-- 配置切面 -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>

</beans>

5.4.4 完全注解方式的声明式事务管理

  • SpringConfig.java
package com.sunxiaping.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.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@ComponentScan(basePackages = "com.sunxiaping")
@EnableTransactionManagement //开启事务
public class SpringConfig {

    /**
     * 连接池
     *
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        druidDataSource.setUrl("jdbc:mysql://192.168.134.100:3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true");
        druidDataSource.setUsername("root");
        druidDataSource.setPassword("123456");
        return dataSource();
    }

    /**
     * JdbcTemplate
     *
     * @return
     */
    @Bean
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        return jdbcTemplate;
    }


    /**
     * 事务管理器
     *
     * @return
     */
    @Bean
    public TransactionManager transactionManager() {
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }

}

6 Spring5新特性

6.1 概述

  • 整个Spring5框架基于JDK8,运行时兼容JDK9,许多不建议使用的类和方法在代码库中删除。
  • Spring5框架自带了通用的日志封装。
    • Spring5框架已经移除了Log4jConfigListener,官方建议使用Log4j2。
  • Spring5框架核心容器支持@Nullable注解。
    • @Nullable可以使用在方法、属性和参数上面。
      • 如果@Nullable用在方法上面,表示方法的返回值可以为null。
      • 如果@Nullable用在属性上面,表示属性值可以为null。
      • 如果@Nullable用在方法参数里面,表示参数可以为null。
  • Spring5核心容器支持函数式风格GenericApplicationContext/AnnotationConfigApplicationContext。
  • Spring5支持整合Junit5。
  • Spring5支持WebFlux。

6.2 Spring5整合Log4j2

  • 导入log4j相关jar包的Maven坐标
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.13.3</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.13.3</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.30</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>2.13.3</version>
</dependency>
  • 创建log4j2的配置文件(log4j2.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成trace时,可以看到log4j2内部各种详细输出-->
<configuration status="INFO">
    <!--先定义所有的appender-->
    <appenders>
        <!--输出日志信息到控制台-->
        <console name="Console" target="SYSTEM_OUT">
            <!--控制日志输出的格式-->
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </console>
    </appenders>
    <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
    <!--root:用于指定项目的根日志,如果没有单独指定Logger,则会使用root作为默认的日志输出-->
    <loggers>
        <root level="info">
            <appender-ref ref="Console"/>
        </root>
    </loggers>
</configuration>
  • 测试:
package com.sunxiaping;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Spring5Test {
    private static final Logger LOGGER = LoggerFactory.getLogger(Spring5Test.class);
    @Test
    public void test() {
        LOGGER.info("info....");
        LOGGER.debug("debug...");
    }
}

6.3 Spring5支持函数式风格

  • 示例:
  • Person.java
package com.sunxiaping;

import org.springframework.stereotype.Component;

@Component
public class Person {

    
    private String name;

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
  • 测试:
package com.sunxiaping;

import org.junit.Test;
import org.springframework.context.support.GenericApplicationContext;

public class Spring5Test {

    /**
     * 函数式风格创建对象,交给Spring管理
     */
    @Test
    public void test() {
        //创建GenericApplicationContext对象
        GenericApplicationContext context = new GenericApplicationContext();
        //调用context的refresh()方法
        context.refresh();
        context.registerBean("person",Person.class,()->new Person());
        //获取在Spring注册的对象
        Person person = context.getBean(Person.class);
        System.out.println(person);
    }
}

6.4 Spring5整合Junit

6.4.1 Spring5整合Junit4

  • 导入junit4和Spring整合junit4相关jar包的Maven坐标:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>
  • 在测试类中,使用注解方式完成
package com.sunxiaping;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//指定Junit的版本
@RunWith(SpringJUnit4ClassRunner.class)
//加载配置文件
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class Spring5Test {

    @Autowired
    private Person person;

    @Test
    public void test(){
        System.out.println(person);
    }
}

6.4.2 Spring5整合Junit5

  • 导入junit5和Spring整合junit4相关jar包的Maven坐标:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>5.2.7.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.6.2</version>
    <scope>test</scope>
</dependency>
  • 在测试类中,使用注解方式完成
package com.sunxiaping;


import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
//加载配置文件
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class Spring5Test {

    @Autowired
    private Person person;

    @Test
    public void test(){
        System.out.println(person);
    }
}

6.5 WebFlux

6.5.1 Spring WebFlux介绍

  • Spring Webflux是Spring5添加的新的模块,用于web开发的,功能和SpringMVC类似,Webflux使用当前一种比较流行的响应式编程而出现的框架。

  • 使用传统的web框架,比如Spring MVC,是基于Servlet容器;Webflux是一种异步非阻塞的框架,异步非阻塞是在Servlet3.1后才开始支持的,Webflux是基于Reactor的相关API实现的。

  • 异步非阻塞:

    • 异步和同步是针对调用者来说的。
      • 当调用者发送请求,如果要等着对方回应之后才做其他的事情,这个现象称为同步。
      • 当调用者发送请求,如果不需要等着对方回应之后就可以做其他的事情,这个现象称为异步。
    • 阻塞和非阻塞是针对被调用者而言的。
      • 当被调用者收到一个请求之后,做完请求任务之后才给出反馈就是阻塞。
      • 当被调用者收到一个请求之后,马上给出反馈然后再去做请求任务就是非阻塞。
  • webflux的特点:

    • 非阻塞式:在有限的资源下,提高系统吞吐量和伸缩性,以Reactor为基础实现响应式编程。
    • 函数式编程:Spring5框架基于JDK8,webflux中可以使用JDK8函数式编程方式实现路由请求。
  • Spring MVC VS Spring Webflux

Spring5

SpringMVC和SpringWebflux都可以使用注解方式,都运行在Tomcat等容器中。

SpringMVC采用命令式编程,SpringWebflux采用异步响应式编程。

6.5.2 响应式编程

6.5.2.1 什么是响应式编程?

  • 响应式编程是一种面向数据流和变化传播的编程范式。这意味着可以在编程语言中很方便地表达静态或动态的数据流,而相关的计算模型会自动将变化的值通过数据流进行传播。
  • 电子表格程序就是响应式编程的一个例子。单元格可以包含字面值或类似"=B1+C1"的公式,而包含公式的单元格的值会依据其他单元格的值的变化而变化。

6.5.2.2 Java8及之前版本

  • 提供了观察者模式的两个类Observer和Observable。

  • 示例:

package com.sunxiaping.springbootspring5.reactor8;

import java.util.Observable;

public class ObserverDemo extends Observable {
    public static void main(String[] args) {
        ObserverDemo observerDemo = new ObserverDemo();
        //添加观察者
        observerDemo.addObserver((o, arg) -> {
            System.out.println("发生了变化");
        });
        observerDemo.addObserver((o, arg) -> {
            System.out.println("收到被观察者的通知,准备发生改变");
        });
        //数据变化
        observerDemo.setChanged();
        //通知
        observerDemo.notifyObservers();
    }
}

6.5.2.3 Reactor实现

  • 响应式编程的操作中,Reactor是满足Reactive规范的一个框架,Webflux的核心是Reactor。
  • Reactor有两个核心类:Mono和Flux,这两个类都实现了接口Publisher,提供丰富的操作符。Flux对象实现发布者,返回N个元素;Mono对象实现发布者,返回0或1个元素。
  • Flux和Mono都是数据流的发布者,使用Flux和Mono都可以发送三种数据信号:元素值,错误信号,完成信号。错误信号和完成信号都代表终止信号,终止信号用来告诉订阅者数据流已经结束了,错误信号终止数据流同时把错误的信息传递给订阅者。

Spring5

  • 示例:演示Flux和Mono
  • 导入reactor的jar包的Maven坐标:
<dependency>
    <groupId>io.projectreactor</groupId>
    <artifactId>reactor-core</artifactId>
    <version>3.1.5.RELEASE</version>
</dependency>
  • ReactorTest.java
package com.sunxiaping.springbootspring5.reactor8;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ReactorTest {
    public static void main(String[] args) {
        //just方法,直接声明
        Flux.just(1,2,3,4);
        Mono.just(1);

        //其他方法
        Integer[] arr = {1,2,3};
        Flux.fromArray(arr);

        List<Integer> list = Arrays.asList(1,2,3);
        Flux.fromIterable(list);

        Stream<Integer> stream = list.stream();
        Flux.fromStream(stream);

    }
}
  • 三种信号的特点:

    • 错误信号和完成信号都是终止信号,不能共存的。
    • 如果没有发送任何元素值,而是直接发送错误或者完成信息,表示是一个空的数据流。
    • 如果没有错误信号,也没有完成信号,表示是无限数据流。
  • 调用just或者其他方法只是申明数据流,数据流并没有发出,只有进行订阅之后才会触发数据流,不订阅什么都不会发生的。

package com.sunxiaping.springbootspring5.reactor8;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class ReactorTest {
    public static void main(String[] args) {
        //just方法,直接声明
        Flux.just(1,2,3,4).subscribe(System.out::println);
        Mono.just(1).subscribe(System.out::println);

        //其他方法
        Integer[] arr = {1,2,3};
        Flux.fromArray(arr).subscribe(System.out::println);

        List<Integer> list = Arrays.asList(1,2,3);
        Flux.fromIterable(list).subscribe(System.out::println);

        Stream<Integer> stream = list.stream();
        Flux.fromStream(stream).subscribe(System.out::println);       
    }
}

6.5.2.4 操作符

  • 对数据流进行一道道的操作,称为操作符。比如工厂的流水线。

  • map:元素映射为新的元素。

Spring5

  • flatMap:元素映射为流。

Spring5

6.5.3 WebFlux的执行流程和核心API

  • SpringWebFlux基于Reactor,默认使用的容器是Netty,Netty是高性能的NIO框架,异步非阻塞的框架。
  • BIO:

Spring5

  • NIO:

Spring5

  • SpringWebFlux执行过程和SpringMVC执行过程类似。

    • SpringWebFlux核心控制器DispatcherHandler,实现了WebHandler接口。
    • WebHandler的源码如下:
    package org.springframework.web.server;
    
    import reactor.core.publisher.Mono;
    
    public interface WebHandler {
        Mono<Void> handle(ServerWebExchange var1);
    }
    
    • DispatcherHandler,实现了handle方法,其源码片段如下:
    public class DispatcherHandler implements WebHandler, ApplicationContextAware {
    	//ServerWebExchange是HTTP的请求信息
        public Mono<Void> handle(ServerWebExchange exchange) {
            return this.handlerMappings == null ? this.createNotFoundError() : Flux.fromIterable(this.handlerMappings).concatMap((mapping) -> {
                return mapping.getHandler(exchange);//根据请求地址获取对应的mapping
            }).next().switchIfEmpty(this.createNotFoundError()).flatMap((handler) -> {
                return this.invokeHandler(exchange, handler);//调用具体的业务方法
            }).flatMap((result) -> {
                return this.handleResult(exchange, result);//处理的结果返回
            });
        }
    }
    
  • SpringWebFlux里面的DispatcherHandler,负责请求的处理。

    • HandlerMapping:请求查询到处理的方法。
    • HandlerAdapter:真正负责请求处理。
    • HandlerResultHandler:响应结果处理。
  • SpringWebFlux实现函数式编程,两个接口:RouterFunction(路由处理)和HandlerFunction(处理函数)。

6.5.4 SpringWebFlux(基于注解编程模型)

  • 示例:以SpringBoot项目为例,使用SpringBoot2.x版本。
  • 导入spring-boot-starter-webflux的jar包的Maven坐标:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
  • User.java
package com.sunxiaping.springbootspring5.domain;

public class User {

    private String username;

    private String gender;

    private Integer age;

    public User() {
    }

    public User(String username, String gender, Integer age) {
        this.username = username;
        this.gender = gender;
        this.age = age;
    }

    public String getUsername() {
        return username;
    }

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

    public String getGender() {
        return gender;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", gender='" + gender + '\'' +
                ", age=" + age +
                '}';
    }
}
  • UserService.java
package com.sunxiaping.springbootspring5.service;

import com.sunxiaping.springbootspring5.domain.User;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

public interface UserService {

    /**
     * 根据id查询用户
     *
     * @param id
     * @return
     */
    Mono<User> findUserById(Integer id);

    /**
     * 查询所有用户
     *
     * @return
     */
    Flux<User> findAllUser();

    /**
     * 添加用户
     *
     * @param userMono
     * @return
     */
    Mono<Void> saveUserInfo(Mono<User> userMono);

}
  • UserServiceImpl.java
package com.sunxiaping.springbootspring5.service.impl;

import com.sunxiaping.springbootspring5.domain.User;
import com.sunxiaping.springbootspring5.service.UserService;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static Map<Integer, User> users = new HashMap<>();

    static {
        users.put(1, new User("lucy", "女", 20));
        users.put(2, new User("marry", "女", 18));
        users.put(3, new User("jack", "男", 45));
    }

    @Override
    public Mono<User> findUserById(Integer id) {
        return Mono.justOrEmpty(users.get(id));
    }

    @Override
    public Flux<User> findAllUser() {
        return Flux.fromIterable(users.values());
    }

    @Override
    public Mono<Void> saveUserInfo(Mono<User> userMono) {
        return userMono.doOnNext((user) -> {
            Integer id = users.size() + 1;
            users.put(id, user);
        }).thenEmpty(Mono.empty());
    }
}
  • UserController.java
package com.sunxiaping.springbootspring5.web;

import com.sunxiaping.springbootspring5.domain.User;
import com.sunxiaping.springbootspring5.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @GetMapping("/user/{id}")
    public Mono<User> getUserId(@PathVariable("id") Integer id) {
        return userService.findUserById(id);
    }


    /**
     * 查询所有的用户信息
     *
     * @return
     */
    @GetMapping("/users")
    public Flux<User> findAllUser() {
        return userService.findAllUser();
    }


    /**
     * 新增用户信息
     *
     * @param user
     * @return
     */
    @PostMapping("/saveUser")
    public Mono<Void> saveUser(@RequestBody User user) {
        Mono<User> userMono = Mono.just(user);
        return userService.saveUserInfo(userMono);
    }
}
上一篇:winserver时间同步服务NTP


下一篇:Spring5--@Indexed注解加快启动速度