xiaohuihui
for me

Spring5

2021-01-16 09:28:20
Word count: 13.9k | Reading time: 68min

Spring5框架

1.Spring框架介绍

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

Spring使用

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

image-20210116103956708

image-20210116104101859

2.IOC容器(Inversion of control)

IOC(Inversion of control):控制反转,把对象创建和对象之间的调用过程,交给Spring进行管理。这种做的好处可以降低耦合度

IOC底层原理

xml解析、工厂模式、反射

过程:

第一步:xml配置文件,配置创建的对象。<bean id="user" class="xhh460.User"></bean>

第二步:创建工厂类(进一步降低耦合度)

1
2
3
4
5
6
7
8
9
10
class UserFactory{
public static User getUser(){
//1.xml解析
String classValue = class属性值;
//2.通过反射创建对象
Class c1 = Class.forName(ClassValue);
//3.
return (User)c1.newInstance();
}
}

IOC接口(BeanFactory)

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

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

    • BeanFactory:IOC容器基本实现,是Spring内部使用的接口,不提供开发人员使用。加载配置文件的时候不会创建对象,在获取对象时才去创建对象。
    • ApplicationContext:BeanFactory接口的子接口,提供更多更强大的功能,一般由开发人员进行使用。加载配置文件时候,就会对配置文件中的对象进行创建。
  3. ApplicationContext接口实现类

    image-20210116123959236

    一个以类为根,一个以系统为根的文件系统。

IOC操作Bean管理

Bean管理指的是两个操作:

  • Spring创建对象

  • Spring注入属性

Bean管理操作有两种方式:

  1. 基于xml配置文件方式实现
  2. 基于注解方式实现

IOC操作Bean管理(基于xml)

image-20210116125829348

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

2.在bean标签有很多属性,介绍常用的属性。

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

3.创建对象时,默认也是执行无参构造方法完成对象创建。

4.DI:依赖注入,就是注入属性

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package xhh460;

/**
* @Author coderYang
* @Date 2021/1/16 13:13
*/
public class Book {
//创建属性
private String bookName;
private String author;

//创建属性对应的set
public void setBookName(String bname) {
this.bookName = bname;
}

public void setAuthor(String author) {
this.author = author;
}
}

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

image-20210116133354602

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

(1)创建类,定义属性,创建属性对应有参构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package xhh460;

/**
* @Author coderYang
* @Date 2021/1/16 13:36
*/
public class Orders {
//属性
private String oName;
private String address;

public Orders(String oName, String address) {
this.oName = oName;
this.address = address;
}
}

​ (2)在spring配置文件配置对象创建,配置构造参数注入

image-20210116134135564

p名称空间注入

  1. 使用p名称空间注入,可以简化基于xml配置。

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

    image-20210116160040659

​ 第二步:进行属性注入,在bean标签里面进行操作。

image-20210116160509207

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

字面量

(1)null值

image-20210116161318110

​ (2)属性值包含特殊符号

image-20210116162005346

注入属性-外部bean

(1)创建两个类:service类和dao类

UserDao.java

1
2
3
4
5
6
7
8
9
package xhh460.dao;

/**
* @Author coderYang
* @Date 2021/1/16 16:26
*/
public interface UserDao {
void update();
}

UserDaoImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
package xhh460.dao;

/**
* @Author coderYang
* @Date 2021/1/16 16:26
*/
public class UserDaoImpl implements UserDao{
@Override
public void update() {
System.out.println("dao update....");
}
}

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package xhh460.service;

import xhh460.dao.UserDao;
import xhh460.dao.UserDaoImpl;

/**
* @Author coderYang
* @Date 2021/1/16 16:25
*/
public class UserService {
private UserDao userDao;

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

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


}

(2)在service调用dao类里面的方法

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package xhh460.service;

import xhh460.dao.UserDao;
import xhh460.dao.UserDaoImpl;

/**
* @Author coderYang
* @Date 2021/1/16 16:25
*/
public class UserService {
private UserDao userDao;

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

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


}

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

image-20210117100616203

注入属性-内部bean

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

一个部门对应多个员工

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

部门类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package xhh460.bean;

/**
* @Author coderYang
* @Date 2021/1/17 10:11
*/
//部门类
public class Dept {
private String dname;

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

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

员工类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package xhh460.bean;

/**
* @Author coderYang
* @Date 2021/1/17 10:12
*/

//员工类
public class Emp {
private String ename;
private String gender;
//部门引用
private Dept dept;

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

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

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

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

image-20210117104146286

注入属性-级联赋值

(1)第一种写法

image-20210117105117253

(2)第二种写法

image-20210117110239077

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

注入数组类型属性
注入List集合属性
注入Map集合属性

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package xhh460.collectiontype;

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

/**
* @Author coderYang
* @Date 2021/1/17 12:32
*/
public class Stu {
//1.数组类型属性
private String[] courses;

//2.List集合类型属性
private List<String> list;

//3.Map集合类型属性
private Map<String,String> maps;

//4.set集合类型属性
private Set<String> sets;

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

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

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

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

java文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package xhh460.collectiontype;

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

/**
* @Author coderYang
* @Date 2021/1/17 12:32
*/
public class Stu {
//1.数组类型属性
private String[] courses;

//2.List集合类型属性
private List<String> list;

//3.Map集合类型属性
private Map<String,String> maps;

//4.set集合类型属性
private Set<String> sets;

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

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

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

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

public void test(){
System.out.println(Arrays.toString(courses));
System.out.println(list);
System.out.println(sets);
System.out.println(maps);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?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="stu" class="xhh460.collectiontype.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>java课程</value>
<value>python课程</value>
</array>
</property>
<!--list类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>李四</value>
</list>
</property>
<!--map类型属性注入-->
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="Python" value="python"></entry>
</map>
</property>
<!--set集合属性注入-->
<property name="sets">
<set>
<value>PHP</value>
<value>C</value>
</set>
</property>
</bean>
</beans>
集合中设置对象类型值

Stu.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package xhh460.collectiontype;

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

/**
* @Author coderYang
* @Date 2021/1/17 12:32
*/
public class Stu {
//1.数组类型属性
private String[] courses;

//2.List集合类型属性
private List<String> list;

//3.Map集合类型属性
private Map<String,String> maps;

//4.set集合类型属性
private Set<String> sets;

//学生所学课程
private List<Course> courseList;

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

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

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

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

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

public void test(){
System.out.println(Arrays.toString(courses));
System.out.println(list);
System.out.println(sets);
System.out.println(maps);
System.out.println(courseList);
}
}

Course.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package xhh460.collectiontype;

/**
* @Author coderYang
* @Date 2021/1/17 13:02
*/
public class Course {
//课程名称
private String cname;

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

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

XML配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?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="stu" class="xhh460.collectiontype.Stu">
<!--数组类型属性注入-->
<property name="courses">
<array>
<value>java课程</value>
<value>python课程</value>
</array>
</property>
<!--list类型属性注入-->
<property name="list">
<list>
<value>张三</value>
<value>李四</value>
</list>
</property>
<!--map类型属性注入-->
<property name="maps">
<map>
<entry key="JAVA" value="java"></entry>
<entry key="Python" value="python"></entry>
</map>
</property>
<!--set集合属性注入-->
<property name="sets">
<set>
<value>PHP</value>
<value>C</value>
</set>
</property>

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

<!--创建多个course对象-->
<bean id="course1" class="xhh460.collectiontype.Course">
<property name="cname" value="Spring5框架课程"></property>
</bean>
<bean id="course2" class="xhh460.collectiontype.Course">
<property name="cname" value="SpringBoot框架课程"></property>
</bean>
</beans>
把集合注入部分提取出来(作为公共部分)

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

(2)使用util标签完成list集合注入提取

Book.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package xhh460.collectiontype;

import java.util.List;

/**
* @Author coderYang
* @Date 2021/1/17 13:20
*/
public class Book {
private List<String> list;

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

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

xml配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.1.xsd">

<!--1.提取list集合类型属性注入-->
<util:list id="bookList">
<value>零基础学java</value>
<value>零基础学c</value>
<value>零基础学python</value>
</util:list>

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

IOC操作Bean管理(FactoryBean)

Spring有两种类型bean,一种是bean,另一种是工厂bean(FactoryBean)

普通bean:在配置文件中定义bean类型就是返回类型

工厂bean:在配置文件定义bean类型可以和返回类型不一样

步骤:

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

bean3.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="myBean" class="xhh460.factorybean.MyBean">

</bean>
</beans>

MyBean.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package xhh460.factorybean;

import org.springframework.beans.factory.FactoryBean;
import xhh460.collectiontype.Course;

/**
* @Author coderYang
* @Date 2021/1/17 14:08
*/
public class MyBean implements FactoryBean<Course> {

@Override
public Course getObject() throws Exception {
Course course = new Course();
course.setCname("数据结构");
return course;
}

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

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

Test.java

1
2
3
4
5
6
@Test
public void testMyBean1(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean3.xml");
Course course = context.getBean("myBean", Course.class);
System.out.println(course.toString());
}

输出:

image-20210117143037017

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

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

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

    image-20210117152113077

如何设置单实例和多实例

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

(2)scope属性值:singleton(默认值),表示单实例对象。prototype:表示多实例对象

配置多实例:

image-20210117152729079

(3)scope的prototype的区别

singleton:加载spring配置文件时候就会创建单实例对象。

prototype:调用getBean方法时创建多实例对象。

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

生命周期是指对象创建到对象销毁的过程

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

bean生命周期演示

image-20210117160245840

bean的后置处理器

生命周期:

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

演示:

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

MyBeanPost.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package xhh460.bean;

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

/**
* @Author coderYang
* @Date 2021/1/17 16:18
*/
public class MyBeanPost implements BeanPostProcessor {
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println("在初始化之前执行的方法");
return bean;
}

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

spring配置文件

1
2
3
4
5
6
7
8
9
10
11
12
<?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="orders" class="xhh460.bean.Orders" init-method="initMethod" destroy-method="destroyMethod">
<property name="oname" value="跑步机"></property>
</bean>

<!--配置后置处理器-->
<bean id="myBeanPost" class="xhh460.bean.MyBeanPost"></bean>
</beans>

Test.java

1
2
3
4
5
6
7
8
9
10
11
public class TestSpring {
@Test
public void testMyBean2(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
Orders orders = context.getBean("orders", Orders.class);
System.out.println("第四步:获取创建bean实例对象");
System.out.println(orders);
//手动让bean实例销毁
((ClassPathXmlApplicationContext) context).close();
}
}

image-20210117162840560

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

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

Emp.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xhh460.autowire;

/**
* @Author coderYang
* @Date 2021/1/17 16:37
*/
public class Emp {
private Dept dept;

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

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

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

Dept.java

1
2
3
4
5
6
7
8
9
10
11
12
package xhh460.autowire;

/**
* @Author coderYang
* @Date 2021/1/17 16:37
*/
public class Dept {
@Override
public String toString() {
return "Dept{}";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?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标签属性autowire,配置自动装配
常用属性值:
byName:根据属性名称注入,注入值bean的id值和类属性名称一样
byType:根据属性类型注入
-->
<bean id="emp" class="xhh460.autowire.Emp" autowire="byName">

</bean>
<!--此处的id和类中属性名称一致-->
<bean id="dept" class="xhh460.autowire.Dept"></bean>
</beans>

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

1.配置连接池

1
2
3
4
5
6
7
8
9
10
11
12
<?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="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/userDb"></property>
<property name="username" value="root"></property>
<property name="password" value="admin@123"></property>
</bean>
</beans>

2.引入外部属性文件配置数据库连接池

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

image-20210117174824167

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

引入context名称空间

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

image-20210117180108646

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

注解:

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

2.注解作用在类上面,方法上面,属性上面。

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

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

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

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

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

第一步 引入依赖jar包

spring-aop-5.2.6.RELEASE.jar

第二步 开启组件扫描

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!--开启组件扫描,去扫描指定包的所有类上的注解
1.如果扫描多个包,则采用,隔开
-->
<context:component-scan base-package="xhh460.dao,xhh460.service"/>
</beans>

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package xhh460.service;

import org.springframework.stereotype.Component;

/**
* @Author coderYang
* @Date 2021/1/17 22:58
*/
//在注解里面的value属性值可以省略不写,默认值是类名称,首字母小写
@Component(value = "userService") //value等同于<bean id="userService" class=""/>中的值域
public class UserService {

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

Test.java

1
2
3
4
5
6
7
8
9
public class TestSpring5 {
@Test
public void testService(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}
开启组件扫描细节配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!--开启组件扫描,去扫描指定包的所有类上的注解
1.如果扫描多个包,则采用,隔开
-->
<context:component-scan base-package="xhh460.dao,xhh460.service"/>


<!--扫描配置方式1:
use-default-filters="false":表示现在不使用默认扫描,自己配置filter
context:include-filter:自己配置扫描哪些内容
-->
<context:component-scan base-package="xhh460" use-default-filters="false">
<!--此处所配置是:只扫描注解为@Controller的类-->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>


<!--扫描配置方式2:
context:exclude-filter:设置哪些内容不进行扫描
-->
<context:component-scan base-package="xhh460">
<!--此处表示扫描不包含注解为@Controller的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
基于注解方式实现属性注入

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

1.把service和dao对象创建,在service和dao类添加创建对象注解

UserDao.java

1
2
3
4
5
6
7
8
9
10
package xhh460.dao;

/**
* @Author coderYang
* @Date 2021/1/18 11:11
*/

public interface UserDao {
public void add();
}

UserDaoImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package xhh460.dao;

import org.springframework.stereotype.Repository;

/**
* @Author coderYang
* @Date 2021/1/18 11:11
*/
@Repository
public class UserDaoImpl implements UserDao{
@Override
public void add() {
System.out.println("dao add..");
}
}

2.在service注入dao对象,在service类添加dao类型属性,在属性上面使用注解

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import xhh460.dao.UserDao;

/**
* @Author coderYang
* @Date 2021/1/17 22:58
*/
//在注解里面的value属性值可以省略不写,默认值是类名称,首字母小写
@Service
public class UserService {

//定义UserDao类型属性,不需要添加set方法
@Autowired //此处根据UserDao类型进行注入
private UserDao userDao;

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

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!--开启组件扫描,去扫描指定包的所有类上的注解
1.如果扫描多个包,则采用,隔开
-->
<context:component-scan base-package="xhh460.dao,xhh460.service"/>

TestSpring5.java

1
2
3
4
5
6
7
8
9
public class TestSpring5 {
@Test
public void testService(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
System.out.println(userService);
userService.add();
}
}

输出:

image-20210118112536064

@Qualifier:根据属性名称进行注入

@Qualifier注解的使用要和@AutoWired一起使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import xhh460.dao.UserDao;

/**
* @Author coderYang
* @Date 2021/1/17 22:58
*/
//在注解里面的value属性值可以省略不写,默认值是类名称,首字母小写
@Service
public class UserService {

//定义UserDao类型属性,不需要添加set方法
@Autowired //此处根据UserDao类型进行注入
@Qualifier(value = "userDaoImpl") //根据名称进行注入
private UserDao userDao;

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

其他代码跟上面一样。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xhh460.service;

import org.springframework.stereotype.Service;
import xhh460.dao.UserDao;

import javax.annotation.Resource;

/**
* @Author coderYang
* @Date 2021/1/17 22:58
*/
//在注解里面的value属性值可以省略不写,默认值是类名称,首字母小写
@Service
public class UserService {

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

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

@Value:注入普通类型属性

直接给属性name赋值abc

image-20210118133132502

完全注解开发

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

SpringConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package xhh460.config;

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

/**
* @Author coderYang
* @Date 2021/1/18 13:35
*/
@Configuration //使用此注解用来标识此类为配置类
@ComponentScan(basePackages = {"xhh460"})
public class SpringConfig {

}

(2)编写测试类

TestSpring5.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package xhh460.testdemo;

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

/**
* @Author coderYang
* @Date 2021/1/17 22:54
*/
public class TestSpring5 {

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

3.Aop(Aspect Oriented Programing)

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

以登录功能为例:

image-20210118135846291

底层原理

Aop底层使用动态代理

  • 有接口情况,使用JDK动态代理

创建接口实现类代理对象,增强类的方法

image-20210118142754741

  • 没有接口情况,使用CGLIB动态代理

创建子类的代理对象,增强类的方法

image-20210118143414671

JDK动态代理

调用newProxyInstance方法

image-20210118144159575

该方法有三个参数:

第一个参数:类加载器

第二个参数:增强方法所在的类,这个类实现的接口,支持多个接口

第三个参数:实现这个接口InvocationHandler,创建代理对象,写增强的方法

编写JDK动态代理代码

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

UserDao.java

1
2
3
4
5
6
7
8
9
10
11
package xhh460;

/**
* @Author coderYang
* @Date 2021/1/18 15:01
*/
public interface UserDao {
public int add(int a,int b);

public String update(String id);
}

(2)创建接口实现类

UserDaoImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package xhh460;

/**
* @Author coderYang
* @Date 2021/1/18 15:04
*/
public class UserDaoImpl implements UserDao{
@Override
public int add(int a, int b) {
return a+b;
}

@Override
public String update(String id) {
return id;
}
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package xhh460;

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

/**
* @Author coderYang
* @Date 2021/1/18 15:06
*/
public class JDKProxy {

public static void main(String[] args) {
//创建接口实现类代理对象
Class[] interfaces = {UserDao.class};
UserDaoImpl userDao = new UserDaoImpl();
UserDao dao = (UserDao)Proxy.newProxyInstance(JDKProxy.class.getClassLoader(),interfaces,new UserDaoProxy(userDao));
int result = dao.add(1,2);
System.out.println(result);
}

}


//创建对象代码
class UserDaoProxy implements InvocationHandler{
//1.把代理对象传递过来
private Object obj;
//有参数构造进行传递
public UserDaoProxy(Object obj){
this.obj = obj;
}

//增强逻辑
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//方法之前处理
System.out.println("方法之前执行..."+method.getName()+"传递的参数=>"+ Arrays.toString(args));
//被增强的方法执行
Object res = method.invoke(obj, args);
//方法之后处理
System.out.println("方法之后执行..."+obj);
return res;
}
}

输出结果:

image-20210118205112275

AOP术语

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

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

通知(增强):实际增强的逻辑部分称为通知(增强)。通知有五种类型:

  1. 前置通知
  2. 后置通知
  3. 环绕通知
  4. 异常通知
  5. 最终通知

切面:是个动作,把通知应用到切入点过程。

AOP操作(准备)

Spring框架一般基于AspectJ实现AOP操作。

什么是AspectJ?

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

Aspect实现AOP操作

  1. 基于xml配置文件实现
  2. 基于注解方式实现(常用)
1.在项目工程中引入AOP相关依赖

image-20210118212408872

2.切入点表达式

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

(2)语法结构:

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

1
2
3
4
5
6
7
8
//示例1:对xhh460.BookDao类里面的add进行增强
execution(* xhh460.BookDao.add(..))

//实例2:对xhh460.BookDao类里面的所有方法进行增强
execution(* xhh460.BookDao.*(...))

//实例3:对xhh460包里面的所有类,所有方法进行增强
execution(* xhh460.*.*(...))

AOP操作(AspectJ注解)

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

User.java

1
2
3
4
5
6
7
8
9
10
11
package xhh460.aopanno;

/**
* @Author coderYang
* @Date 2021/1/18 21:37
*/
public class User {
public void add(){
System.out.println("add...");
}
}
2.创建增强类(编写增强逻辑)

在增强类里面创建方法,让不同的方法代表不同的通知类型。

UserProxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package xhh460.aopanno;

/**
* @Author coderYang
* @Date 2021/1/18 21:39
*/
//增强的类
public class UserProxy {
//前置通知
public void before(){
System.out.println("before.......");
}
}
3.进行通知的设置

(1)在spring的配置文件中,开启注解扫描

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="xhh460.aopanno"/>

</beans>

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

image-20210118215404725

image-20210118215417346

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

image-20210118215520950

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

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="xhh460.aopanno"/>

<!--开启Aspect生成代理对象-->
<aop:aspectj-autoproxy/>

</beans>
4.配置不同类型的通知

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

UserProxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package xhh460.aopanno;

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

/**
* @Author coderYang
* @Date 2021/1/18 21:39
*/
//增强的类
@Component
@Aspect
public class UserProxy {
//前置通知
//@Before注解表示作为前置通知
@Before(value = "execution(* xhh460.aopanno.User.add(..))")
public void before(){
System.out.println("before.......");
}

//后置通知(返回通知)
@AfterReturning(value = "execution(* xhh460.aopanno.User.add(..))")
public void afterReturning(){
System.out.println("afterReturning........");
}

//最终通知
@After(value = "execution(* xhh460.aopanno.User.add(..))")
public void after(){
System.out.println("after........");
}

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

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

}

TestAop.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.aopanno.User;

/**
* @Author coderYang
* @Date 2021/1/18 22:02
*/
public class TestAop {
@Test
public void testAopAnno(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = context.getBean("user", User.class);
user.add();
}
}

输出结果:

image-20210118221354094

如果方法有异常,则输出:

image-20210118221753421

5.相同切入点抽取

使用@Pointcut注解来进行相同切入点抽取。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package xhh460.aopanno;

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

/**
* @Author coderYang
* @Date 2021/1/18 21:39
*/
//增强的类
@Component
@Aspect
public class UserProxy {

//相同切入点抽取
@Pointcut(value = "execution(* xhh460.aopanno.User.add(..))")
public void printDemo(){

}

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

//后置通知(返回通知)
@AfterReturning(value = "printDemo()")
public void afterReturning(){
System.out.println("afterReturning........");
}

//最终通知
@After(value = "printDemo()")
public void after(){
System.out.println("after........");
}

//异常通知
@AfterThrowing(value = "printDemo()")
public void afterThrowing(){
System.out.println("afterThrowing........");
}

//环绕通知
@Around(value = "printDemo()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前........");
//被增强的方法
proceedingJoinPoint.proceed();
System.out.println("环绕之后........");
}

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

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

User.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package xhh460.aopanno;

import org.springframework.stereotype.Component;

/**
* @Author coderYang
* @Date 2021/1/18 21:37
*/
//被增强类
@Component
public class User {
public void add(){
System.out.println("add...");
}
}

UserProxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package xhh460.aopanno;

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

/**
* @Author coderYang
* @Date 2021/1/18 21:39
*/
//增强的类
@Component
@Aspect
@Order(3) //设置优先级为3
public class UserProxy {

//相同切入点抽取
@Pointcut(value = "execution(* xhh460.aopanno.User.add(..))")
public void printDemo(){

}

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

//后置通知(返回通知)
@AfterReturning(value = "printDemo()")
public void afterReturning(){
System.out.println("afterReturning........");
}

//最终通知
@After(value = "printDemo()")
public void after(){
System.out.println("after........");
}

//异常通知
@AfterThrowing(value = "printDemo()")
public void afterThrowing(){
System.out.println("afterThrowing........");
}

//环绕通知
@Around(value = "printDemo()")
public void around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕之前........");
//被增强的方法
proceedingJoinPoint.proceed();
System.out.println("环绕之后........");
}

}

PersonProxy.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package xhh460.aopanno;

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

/**
* @Author coderYang
* @Date 2021/1/19 10:59
*/
@Component
@Aspect
@Order(1) //设置优先级为1
public class PersonProxy {
//前置通知
@Before(value = "execution(* xhh460.aopanno.User.add(..))")
public void afterRetuning(){
System.out.println("Person Before.......");
}
}

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--开启注解扫描-->
<context:component-scan base-package="xhh460.aopanno"/>

<!--开启Aspect生成代理对象-->
<aop:aspectj-autoproxy/>

</beans>

TestAop.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.aopanno.User;

/**
* @Author coderYang
* @Date 2021/1/18 22:02
*/
public class TestAop {
@Test
public void testAopAnno(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
User user = context.getBean("user", User.class);
user.add();
}
}

输出结果:

image-20210119110807250

7.aop完全注解开发

编写配置文件类(取代xml配置文件)

ConfigAop.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package xhh460.config;

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

/**
* @Author coderYang
* @Date 2021/1/19 11:23
*/
@Configuration
@ComponentScan(basePackages = {"xhh460"})
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class ConfigAop {
}

TestAop.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.aopanno.User;
import xhh460.aopxml.Book;
import xhh460.config.ConfigAop;

/**
* @Author coderYang
* @Date 2021/1/18 22:02
*/
public class TestAop {

@Test
public void testAopAnno(){
ApplicationContext context = new AnnotationConfigApplicationContext(ConfigAop.class);
User user = context.getBean("user",User.class);
user.add();
}
}

AOP操作(AspectJ配置文件)

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

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

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

4.JdbcTemplate

概念:

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

JdbcTemplate配置

1.引入相关依赖jar包

image-20210119161018221

2.在spring配置文件配置数据库连接池

image-20210119163641656

3.配置JdbcTemplate对象,注入DataSource

image-20210119164148641

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

在配置文件中开启组件扫描

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

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


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

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

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

</beans>
  • Service

BookService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.BookDao;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;
}
  • Dao

BookDao.java

1
2
3
4
5
6
7
8
package xhh460.dao;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
public interface BookDao {
}

BookImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package xhh460.dao;

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

/**
* @Author coderYang
* @Date 2021/1/19 16:46
*/
@Repository
public class BookImpl {
//注入jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;

}

JdbcTemplate操作数据库

增删改操作

项目目录:

image-20210119183517818

(1)对应数据库创建实体类

Book.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package xhh460.entity;

/**
* @Author coderYang
* @Date 2021/1/19 18:04
*/
public class Book {
private String bookId;
private String Bookname;
private String Bstatus;

public void setBookId(String bookId) {
this.bookId = bookId;
}

public void setBookname(String bookname) {
Bookname = bookname;
}

public void setBstatus(String bstatus) {
Bstatus = bstatus;
}

public String getBookId() {
return bookId;
}

public String getBookname() {
return Bookname;
}

public String getBstatus() {
return Bstatus;
}
}

(2)编写Service和Dao

1.在dao进行数据库添加操作

2.调用JdbcTemplate对象里面的update方法实现添加操作

1
2
3
//update方法有两个参数
//第一个参数:sql语句
//第二个参数:可变参数,设置sql语句值

BookDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package xhh460.dao;

import xhh460.entity.Book;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
public interface BookDao {
void add(Book book);

void updateBook(Book book);

void delete(String id);
}

BookImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package xhh460.dao;

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

/**
* @Author coderYang
* @Date 2021/1/19 16:46
*/
@Repository
public class BookImpl implements BookDao{
//注入jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public void add(Book book) {
//1.创建sql语句
String sql = "insert into t_book values(?,?,?)";
//2.调用方法实现
Object[] args = {book.getBookId(), book.getBookname(), book.getBstatus()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}

@Override
public void updateBook(Book book) {
//1.创建sql语句
String sql = "update t_book set username=?,ustatus=? where user_id=?";
Object[] args = {book.getBookname(),book.getBstatus(),book.getBookId()};
int update = jdbcTemplate.update(sql, args);
System.out.println(update);
}

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

BookService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.BookDao;
import xhh460.entity.Book;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;

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

//修改的方法
public void updateBook(Book book){
bookDao.updateBook(book);
}

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

TestBook.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.entity.Book;
import xhh460.service.BookService;

/**
* @Author coderYang
* @Date 2021/1/19 18:24
*/
public class TestBook {
@Test
public void testJdbcTemplate(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();
//添加
// book.setBookId("1");
// book.setBookname("零基础学java");
// book.setBstatus("a");
// bookService.addBook(book);

//修改
// book.setBookId("1");
// book.setBookname("jvm");
// book.setBstatus("可用");
// bookService.updateBook(book);


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

结果:

1.数据添加成功

image-20210119183957967

2.数据修改成功

image-20210119185431775

3.数据删除成功

image-20210119185515073

查询操作

(1)查询返回某个值

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

2.使用JdbcTemplate实现查询返回某个值

dao层的文件:

image-20210119193252592

service层的文件:

image-20210119193402075

TestBook.java文件:

image-20210119194043994

(2)查询返回对象

注意:此方法的有个参数BeanPropertyRowMapper<T> rowMapper底层默认调用的是set方法,所以在此处我们需要把Book实体的各个成员名字对应数据库中的各个成员名字。

image-20210119202910417

image-20210119202918703

1.场景:查询图书详情

2.JdbcTemplate实现查询返回对象

BookService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.BookDao;
import xhh460.entity.Book;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;

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

//修改的方法
public void updateBook(Book book){
bookDao.updateBook(book);
}

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

//查询表中的记录数
public int findCount(){
return bookDao.selectCount();
}


//查询返回对象
public Book findOne(String id){
return bookDao.findBookInfo(id);
}
}

Dao层BookImpl.java

image-20210119202658034

TestBook.java

image-20210119202725424

输出结果:

image-20210119202942987

(3)查询返回集合

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

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

BookService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.BookDao;
import xhh460.entity.Book;

import java.util.List;

/**
* @Author coderYang
* @Date 2021/1/19 16:45
*/
@Service
public class BookService {
//注入dao
@Autowired
private BookDao bookDao;

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

//修改的方法
public void updateBook(Book book){
bookDao.updateBook(book);
}

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

//查询表中的记录数
public int findCount(){
return bookDao.selectCount();
}


//查询返回对象
public Book findOne(String id){
return bookDao.findBookInfo(id);
}

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

Dao层的BookImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package xhh460.dao;

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 xhh460.entity.Book;

import java.util.List;

/**
* @Author coderYang
* @Date 2021/1/19 16:46
*/
@Repository
public class BookImpl implements BookDao{
//注入jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;

@Override
public List<Book> findAllBook() {
//sql语句
String sql = "select * from t_book";
//调用方法
//query(String sql,RowMapper<T> rowMapper,Object... args)
//第一个参数sql,第二个参数:RowMapper是个接口,返回不同的类型数据,使用这个接口里面实现完成数据封装,第三个参数sql语句值
List<Book> bookList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
return bookList;
}
}

TestBook.java

image-20210119204152782

批量操作

批量操作表里面的多条记录

批量增加

批量操作方法:batchUpdate(String sql,List<Object[]> batchArgs)

第一个参数:sql语句

第二个参数:List集合,添加多条记录数据

Dao层BookImpl.java

image-20210119210707313

BookService.java

image-20210119213012023

TestBook.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.entity.Book;
import xhh460.service.BookService;

import java.util.ArrayList;
import java.util.List;

/**
* @Author coderYang
* @Date 2021/1/19 18:24
*/
public class TestBook {
@Test
public void testJdbcTemplate(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
BookService bookService = context.getBean("bookService", BookService.class);
Book book = new Book();

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

结果:数据添加成功

image-20210119213057912

批量修改

Dao层BookImpl.java

image-20210119214040350

BookService.java

image-20210119214102701

TestBook.java

image-20210119214131662

结果:修改成功

image-20210119214140993

批量删除操作

Dao层的BookImpl.java

image-20210119215023322

BookService.java

image-20210119215043251

TestBook.java

image-20210119215055074

结果:删除成功

image-20210119215139269

5.事务操作

事务是数据库操作最基本单元,逻辑上的一组操作,要么都超过,如果有一个失败则全部失败。

事务四个特性(ACID)

  1. 原子性
  2. 一致性
  3. 隔离性
  4. 持久性

事务搭建环境

image-20210120123620174

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

image-20210120124250778

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

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

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

dao层次文件

UserDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package xhh460.dao;

/**
* @Author coderYang
* @Date 2021/1/20 12:57
*/
public interface UserDao {
//多钱
public void addMoney();
//少钱
public void reduceMoney();

}

UserDaoImpl.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package xhh460.dao;

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

/**
* @Author coderYang
* @Date 2021/1/20 12:57
*/
@Repository
public class UserDaoImpl implements UserDao{
//注入jdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate;

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

}

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

}

service层文件:

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.UserDao;

/**
* @Author coderYang
* @Date 2021/1/20 12:57
*/

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

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

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

配置文件:

jdbc.properties

1
2
3
4
prop.driverClassName=com.mysql.jdbc.Driver
prop.url=jdbc:mysql://localhost:3306/user_db
prop.username=root
prop.password=admin@123

bean1.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

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


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

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

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

</beans>

测试类文件

TestAccount.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package xhh460.test;

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

/**
* @Author coderYang
* @Date 2021/1/20 13:24
*/
public class TestAccount {
@Test
public void testAccount(){
ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");
UserService userService = context.getBean("userService", UserService.class);
userService.accountMoney();
}
}

结果:

image-20210120133508281

问题分析:

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

如果在此处出现异常,那么mary不会收到100块。

image-20210120134358417

结果就是:

image-20210120134341872

大体解决思路:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xhh460.dao.UserDao;

/**
* @Author coderYang
* @Date 2021/1/20 12:57
*/

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



//转账的方法
public void accountMoney(){

try {
//第一步:开启事务

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

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

//mary多100
userDao.addMoney();

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

}
}

Spring事务管理介绍

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

2.在Spring进行事务管理操作:编程式事务管理声明式事务管理(推荐)

3.声明式事务管理:

(1)基于注解方式(推荐)

​ (2)基础xml配置方式

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

5.Spring事务管理API

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

image-20210120140848212

注解声明式事务管理

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

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


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

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

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


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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

(2)开启事务注解

image-20210120142420712

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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package xhh460.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xhh460.dao.UserDao;

/**
* @Author coderYang
* @Date 2021/1/20 12:57
*/

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

//转账的方法
public void accountMoney(){

//lucy少100
userDao.reduceMoney();

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

//mary多100
userDao.addMoney();

}
}

此处注意数据库的存储引擎要改成InnoDB,否则事务不起作用。

TestAccount.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package xhh460.test;

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

/**
* @Author coderYang
* @Date 2021/1/20 13:24
*/
public class TestAccount {

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

结果:控制台报错,数据库信息不变,体现了事务的特点。

image-20210120184629839

image-20210120184618423

声明式事务管理参数配置

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

image-20210120184948304

propagation:事务传播行为,指的是有事务的方法调用没事务的方法,或者没事务的方法调用有事务的方法,或者有事务的方法调用有事务的方法。

image-20210120191909706

在Spring框架中事务传播行为有七种

传播属性 描述
REQUIRED 如果有事务在运行,当前方法就在这个事务内运行,否则,就启动一个新的事务,并在自己的事务内运行
REQUIRED_NEW 当前的方法必须启动新事物,并在它自己的事务内运行,如果有事务正在运行,应该将它挂起
SUPPORTS 如果有事务在运行,当前的方法就在这个事务内运行,否则它不可以运行在事务中
NOT_SUPPORT 当前的方法不应该运行在事务中,如果有运行的事务,将它挂起
MANDATORY 当前的方法必须运行在事务内部,如果没有正在运行的事务,就抛出异常
NEVER 当前的方法不应该运行在事务中,如果有运行的事务,就抛出异常
NESTED 如果有事务在运行,当前的方法就应该在这个事务的嵌套事务内运行。否则,就启动一个新事务,并在它自己的事务内运行。

image-20210120192104094

isolation:事务隔离级别

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

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

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

(4)虚读:一个未提交事务读取到另一个事务添加的数据。

通过设置事务隔离性级别,可以解决以上读的问题。

脏读 不可重复读 幻读
READ UNCOMMITTED(读未提交)
READ COMMITTED(读已提交)
REPEATABLE READ(可重复读)
SERIALIZABLE(串行化)

image-20210120194858938

timeout:超过时间

(1)事务需要在一定的时间内进行提交,如果不提交进行回滚

(2)默认值是-1,时间以秒为单位

readOnly:是否只读

(1)读:查询操作。写:添加修改操作

(2)readOnly:默认值false,表示可以查询,可以进行添加修改删除操作。

(3)设置readOnly值是true的话,只能查询

rollbackFor:回滚

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

noRollbackFor:不回滚

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

XML声明式事务管理

1.在Spring配置文件中进行配置

2.配置通知

3.配置切入点和切面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

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


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

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

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


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

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

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

完全注解开发

1.创建配置类,使用配置类替代xml配置文件

TxConfig.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package xhh460.config;

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

import javax.sql.DataSource;

/**
* @Author coderYang
* @Date 2021/1/20 20:51
*/

@Configuration //配置类
@ComponentScan(basePackages = "xhh460") //开启组件扫描
@EnableTransactionManagement //开启事务
public class TxConfig {
//创建数据库连接池
@Bean
public DruidDataSource getDruidDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/user_db");
dataSource.setUsername("root");
dataSource.setPassword("admin@123");
return dataSource;
}

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

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

}

TestAccount.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package xhh460.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import xhh460.config.TxConfig;
import xhh460.service.UserService;

/**
* @Author coderYang
* @Date 2021/1/20 13:24
*/
public class TestAccount {

@Test
public void testAccount3(){
ApplicationContext context = new AnnotationConfigApplicationContext(TxConfig.class);
UserService userService = context.getBean("userService", UserService.class);
userService.accountMoney();
}
}

6.Spring5框架新功能

日志封装功能

1.Spring5.0框架自带了通用的日志封装

(1)Spring5已经移除了Log4jConfigListener,官方建议使用Log4j2

(2)Spring5框架整合了Log4j2

第一步:引入相关的jar包

image-20210121125702116

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="UTF-8"?>
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status用于设置log4j2自身内部的信息输出,可以不设置,当设置成true时,可以看到log4j2内部各种纤细输出-->
<Configuration status="DEBUG">
<!--先定义所有的appender-->
<Appenders>
<!--输出日志信息到控制台-->
<Console name="Console" target="SYSTEM_OUT">
<!--控制日志输出的格式-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<!--然后定义logger,只有定义了logger并引入appender,appender才会生效-->
<!--root:用于执行项目的根日志,如果没有单独指定logger,则会使用root作为默认的日志输出-->
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

自定义输出日志

UserLog.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package xhh460.test;

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

/**
* @Author coderYang
* @Date 2021/1/21 12:32
*/
public class UserLog {
private static final Logger log = LoggerFactory.getLogger(UserLog.class);

public static void main(String[] args) {
log.info("hello log4j2");
log.warn("hello log4j2");
}
}

@Nullable注解

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

(1)@Nullable注解可以使用在方法上面,属性上面,参数上面,表示方法返回可以为空,属性值可以为空,参数值可以为空。

(2)注解用在方法上面,方法返回值可以为空

image-20210122095346135

(3)注解使用在方法参数里面,表示方法参数可以为空

image-20210122095809858

(4)注解使用在属性上面,属性值可以为空。

image-20210122100122750

函数式风格GenericApplicationContext

image-20210122140728622

支持整合JUnit5

整合JUnit4

第一步:引入Spring相关针对测试依赖

image-20210122141447604

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

JUnit4.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package xhh460.test;

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;
import xhh460.service.UserService;

/**
* @Author coderYang
* @Date 2021/1/22 14:18
*/

@RunWith(SpringJUnit4ClassRunner.class) //指定单元测试框架
@ContextConfiguration("classpath:bean1.xml") //加载配置文件
public class JUnit4 {
@Autowired
private UserService userService;

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

第一步:引入相关jar包

image-20210122154334919

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package xhh460.test;

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;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import xhh460.service.UserService;

/**
* @Author coderYang
* @Date 2021/1/22 15:41
*/
//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:bean1.xml")

//使用复合注解替代上面两个注解完成整合
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class JUnit5 {
@Autowired
private UserService userService;

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

SpringWebflux

1.SpringWebflux介绍

2.响应式编程

3.Webflux执行流程和核心API

Author: 小灰灰

Link: http://xhh460.github.io/2021/01/16/Spring5/

Copyright: All articles in this blog are licensed.

< PreviousPost
Mybatis
NextPost >
Maven
CATALOG
  1. 1. Spring5框架
    1. 1.1. 1.Spring框架介绍
    2. 1.2. 2.IOC容器(Inversion of control)
      1. 1.2.1. IOC底层原理
      2. 1.2.2. IOC接口(BeanFactory)
      3. 1.2.3. IOC操作Bean管理
        1. 1.2.3.1. IOC操作Bean管理(基于xml)
          1. 1.2.3.1.1. 第一种注入方式:使用set方法进行注入
          2. 1.2.3.1.2. 第二种注入方式:使用有参数构造进行注入
          3. 1.2.3.1.3. 字面量
          4. 1.2.3.1.4. 注入属性-外部bean
          5. 1.2.3.1.5. 注入属性-内部bean
          6. 1.2.3.1.6. 注入属性-级联赋值
        2. 1.2.3.2. IOC操作Bean管理(XML注入集合属性)
          1. 1.2.3.2.1. 注入数组类型属性
          2. 1.2.3.2.2. 注入List集合属性
          3. 1.2.3.2.3. 注入Map集合属性
          4. 1.2.3.2.4. 集合中设置对象类型值
          5. 1.2.3.2.5. 把集合注入部分提取出来(作为公共部分)
        3. 1.2.3.3. IOC操作Bean管理(FactoryBean)
        4. 1.2.3.4. IOC操作Bean管理(Bean作用域)
        5. 1.2.3.5. IOC操作Bean管理(Bean生命周期)
          1. 1.2.3.5.1. bean生命周期
          2. 1.2.3.5.2. bean的后置处理器
        6. 1.2.3.6. IOC操作Bean管理(xml自动装配)
        7. 1.2.3.7. IOC操作Bean管理(外部属性文件)
        8. 1.2.3.8. IOC操作Bean管理(基于注解)
          1. 1.2.3.8.1. 基于注解方式实现对象的创建
          2. 1.2.3.8.2. 开启组件扫描细节配置
          3. 1.2.3.8.3. 基于注解方式实现属性注入
          4. 1.2.3.8.4. 完全注解开发
      4. 1.2.4. 3.Aop(Aspect Oriented Programing)
        1. 1.2.4.1. 底层原理
        2. 1.2.4.2. JDK动态代理
        3. 1.2.4.3. AOP术语
        4. 1.2.4.4. AOP操作(准备)
          1. 1.2.4.4.1. 1.在项目工程中引入AOP相关依赖
          2. 1.2.4.4.2. 2.切入点表达式
        5. 1.2.4.5. AOP操作(AspectJ注解)
          1. 1.2.4.5.1. 1.创建类,在类里面定义方法
          2. 1.2.4.5.2. 2.创建增强类(编写增强逻辑)
          3. 1.2.4.5.3. 3.进行通知的设置
          4. 1.2.4.5.4. 4.配置不同类型的通知
          5. 1.2.4.5.5. 5.相同切入点抽取
          6. 1.2.4.5.6. 6.多个增强类对同一个方法进行增强,设置增强优先级
          7. 1.2.4.5.7. 7.aop完全注解开发
        6. 1.2.4.6. AOP操作(AspectJ配置文件)
      5. 1.2.5. 4.JdbcTemplate
        1. 1.2.5.1. JdbcTemplate配置
        2. 1.2.5.2. JdbcTemplate操作数据库
          1. 1.2.5.2.1. 增删改操作
          2. 1.2.5.2.2. 查询操作
          3. 1.2.5.2.3. 批量操作
      6. 1.2.6. 5.事务操作
        1. 1.2.6.1. 事务搭建环境
        2. 1.2.6.2. Spring事务管理介绍
        3. 1.2.6.3. 注解声明式事务管理
        4. 1.2.6.4. 声明式事务管理参数配置
        5. 1.2.6.5. XML声明式事务管理
        6. 1.2.6.6. 完全注解开发
      7. 1.2.7. 6.Spring5框架新功能
        1. 1.2.7.1. 日志封装功能
        2. 1.2.7.2. @Nullable注解
        3. 1.2.7.3. 函数式风格GenericApplicationContext
        4. 1.2.7.4. 支持整合JUnit5
          1. 1.2.7.4.1. 整合JUnit4
          2. 1.2.7.4.2. 整合JUnit5
        5. 1.2.7.5. SpringWebflux