PDF文档下载
https://wwm.lanzouw.com/iIlOyydm6ch
密码:8rui
文章目录
Spring5
1.、Spring
spring是一个思想的学习,有两大思想。
- IOC
- AOP
1.1、简介
-
Spring ——> 春天,为开源软件带来了春天
-
2002,首次推出了Spring框架的雏形:interface21框架!
-
Spring框架以interface21框架为基础,经过重新设计,并不断丰富其内涵,于2004年3月24日发布了1.0正式版
-
Rod Johnson ,Spring Framework创始人,著名作者。很难想象Rod Johnson的学历,真的让好多人大吃一惊,他是悉尼大学的博士,然而他的专业不是计算机,而是音乐学。
-
目的:解决企业应用开发的复杂性
-
Spring的理念:使用现有的技术更加容易使用,本身是一个大杂烩,整合了现有的技术框架!
-
SSH:Struct2 + Spring + Hibernate(全自动持久化框架)!
-
SSM:SpringMVC + Spring + MyBatis(半自动持久化框架,可自定义性质更强)!
spring官网: https://spring.io/projects/spring-framework#overview
官方下载: https://repo.spring.io/release/org/springframework/spring/
GitHub: https://github.com/spring-projects/spring-framework
Spring Web MVC: spring-webmvc最新版
Spring Web MVC和Spring-JDBC的pom配置文件:
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
1.2、优点
- Spring是一个开源的免费的框架(容器)!
- Spring是一个轻量级的、非入侵式的框架!
- 特性:控制反转(IoC),面向切面编程(AOP)
- 支持事务的处理,对框架整合的支持!(几乎市面上所有热门框架都能整合进去)!
总结一句话:Spring就是一个轻量级的控制反转(IoC)和面向切面编程(AOP)的框架!
1.3、组成
Spring7大模块
1.4、扩展
Spring官网介绍 :现代化的java开发 -> 基于Spring的开发!
- Spring Boot
- 一个快速开发的脚手架
- 脚手架:和框架一样
- 基于SpringBoot可以快速开发单个微服务
- 约定大于配置!
- 一个快速开发的脚手架
- Spring Cloud
- SpringCloud是基于SpringBoot实现的!
因为现在大多数公司都在使用SpringBoot进行快速开发,学习SpringBoot的前提,需要完全掌握Spring及SpringMVC!承上启下的作用!
弊端:
发展了太久之后,违背了原来的理念!配置十分繁琐,人称:“配置地狱!“
2、IoC(控制反转)理论推导 【重点】
IOC是一种编程思想,由主动的编程变成被动的接收.
什么是IOC?
- 提供一个set接口
传统的调用
-
UserDao
package dao; public interface UserDao { void getUser(); }
-
UserDaoImp
package dao; public class UserDaoImpl implements UserDao{ public void getUser() { System.out.println("默认获取用户数据"); } }
-
UserSevice
package Service; public interface UserService { void getUser(); }
-
UserServiceImp
作用:调dao层
package Service; import dao.UserDao; import dao.UserDaoImpl; public class UserServiceImpl implements UserService{ UserDao userDao = new UserDaoImpl(); public void getUser(){ userDao.getUser(); } }
-
测试
package holle0;
import Service.UserService;
import Service.UserServiceImpl;
public class MyTest0 {
public static void main(String[] args) {
// 用户实际调用的是业务层,dao层他们不需要接触
UserService userService = new UserServiceImpl();
userService.getUser();
}
}
====
默认获取用户数据
在我们之前的业务中,用户的需求可能会影响我们原来的代码,我们需要根据用户的需求去修改原代码!如果程序代码量十分大,修改一次的成本代价十分昂贵!
改良后:
我们使用一个Set接口实现。已经发生了革命性的变化!
//在Service层的实现类(UserServiceImpl)增加一个Set()方法
//利用set动态实现值的注入!
//DAO层并不写死固定调用哪一个UserDao的实现类
//而是通过Service层调用方法设置实现类!
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
set()方法实际上是动态改变了 UserDao userDao 的 初始化部分(new UserDaoImpl())
测试中加上
userService.setUserDao(new UserDaoImpl());
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!(主动权在客户手上)
思想:
本质上解决了问题,程序员不用再去管理对象的创建
系统的耦合性大大降低,可以更专注在业务的实现上
这是IoC(控制反转)的原型,反转(理解):主动权交给了用户
IoC本质
**控制反转loC(Inversion of Control),是一种设计思想,DI(依赖注入)是实现loC的一种方法,**也有人认为DI只是loC的另一种说法。【我们的所有方法都用依赖注入机制实现的 】
没有loC的程序中,我们使用面向对象编程,对象的创建与对象间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,
个人认为,所谓控制反转就是:获得依赖对象的方式反转了。
loC是Spring框架的核心内容使用多种方式完美的实现了loC,可以使用XML配置,也可以使用注解,新版本的Spring也可以零配置实现loC。
Spring容器在初始化时先读取配置文件,根据配置文件或元数据创建与组织对象存入容器中,程序使用时再从loc容器中取出需要的对象。
采用XML方式配置Bean的时候,Bean的定义信息是和实现分离的,而采用注解的方式可以把两者合为一体,Bean的定义信息直接以注解的形式定义在实现类中,从而达到了零配置的目的。
控制反转是一种通过描述(XML或注解)并通过第三方去生产或获取特定对象的方式。在Spring中实现控制反转的是loC容器,其实现方法是依赖注入(Dependency Injection,DIl)。
3、HelloSpring
第一个程序
在父模块中导入jar包
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
pojo的Hello.java
package com.yin.pojo;
public class Hello {
private String str;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
@Override
public String toString() {
return "Hello{" +
"str='" + str + '\'' +
'}';
}
}
在resource里面的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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用Spring来创建对象,在Spring中这些都成为Bean
原来的写法:
类型 变量名 = new 类型();
Hello hello = new Hello();
bean = 对象 相当于: new Hello
spring写法:
id = 变量名
class = new 的对象
property:相当于,给对象中的属性设置一个值!
-->
<bean id="hello" class="com.yin.pojo.Hello">
<property name="str" value="Spring"/>
</bean>
</beans>
测试类MyTest
import com.yin.pojo.Hello;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//固定的 获取spring的上下文对象!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
// 我们的对象现在都在Spring中管理了,我们要使用,直接去spring里面取出来就可以
Hello hello = (Hello) context.getBean("hello");
System.out.println(hello.toString());
}
}
======输出========
Hello{str='Spring'}
核心用set注入,所以必须要有下面的set()方法
//Hello类
public void setStr(String str) {
this.str = str;
}
思考问题:
-
Hello 对象是谁创建的?
- hello对象是由Spring创建的
-
Hello对象的属性是怎么设置的?
- hello对象的属性是由Spring容器设置的, 通过DI设置
这个过程就叫控制反转:
-
控制:谁来控制对象的创建,
- 传统应用程序的对象(new)是由程序本身控制创建的,
- 使用Spring后,对象是由Spring来创建的
-
反转:
- 程序本身不创建对象,而变成被动的接收对象.
-
依赖注入∶
- 就是利用set方法来进行注入的
- 必须要有set方法!
IOC:
- IOC是一种编程思想,由主动的编程变成被动的接收.
- loC:对象由Spring 来创建,管理,装配!
可以通过newClassPathXmlApplicationContext去浏览一下底层源码.
OK,到了现在,我们彻底不用再程序中去改动了,
要实现不同的操作,只需要在xml配置文件中进行修改,
弹幕评论里面的理解:
-
原来这套程序是:
- 你写好菜单,买好菜,客人来了自己把菜炒好招待,就相当于你请人吃饭
-
现在这套程序是:
- 你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来
-
IoC:
- 炒菜这件事,不再由你自己来做,而是委托给了第三方__餐厅来做
-
此时的区别就是:
- 如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来
修改上一个module
在前面第一个module试试引入Spring
配置文件中新建文件 beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="mysqlImpl" class="com.yin.dao.UserDaoMysqlImpl"/>
<bean id="daoImpl" class="com.yin.dao.UserDaoImpl"/>
<bean id="UserServiceImpl" class="com.yin.service.UserServiceImpl">
<property name="userDao" ref="daoImpl"/>
</bean>
<!--
ref:引用spring容器中已经创建好的对象
value:具体的值,基本数据类型!
-->
</beans>
第一个module改良后测试
import com.yin.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext:拿到spring的容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
//需要什么就直接get什么
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("UserServiceImpl");
userServiceImpl.getUser();
}
}
===============
默认获取用户数据
总结:
Spring的使用步骤:
-
所有的类都要装配的beans.xml 里面;
-
所有的bean 都要通过容器去取;
-
容器里面取得的bean,拿出来就是一个对象,用对象调用方法即可;
-
【我们创建的所有类,都会在spring中注册】
4、IoC创建对象的方式
使用无参构造创建对象,默认。
实体类
package com.yin.pojo;
public class User {
private String name;
public User(){
System.out.println("User的无参构造");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void show(){
System.out.println("name:"+name);
}
}
beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--使用set方法注入-->
<bean id="user" class="com.yin.pojo.User">
<property name="name" value="小尹"/>
</bean>
</beans>
测试
import com.yin.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//拿到容器
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = (User) context.getBean("user");
user.show();
}
}
========
User的无参构造
name:小尹
使用有参构造创建对象
三种方式:
- 下标赋值
index指的是有参构造中参数的下标,下标从0开始;
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--第一种,下标赋值-->
<bean id="user" class="com.yin.pojo.User">
<constructor-arg index="0" value="小尹"/>
</bean>
</beans>
- 参数类型赋值(不建议使用)
有问题,假设两个参数都是string,就不行了
<!--第二种,参数类型赋值,不建议使用-->
<bean id="user" class="com.yin.pojo.User">
<constructor-arg type="java.lang.String" value="小尹"/>
</bean>
- 直接通过参数名(掌握)
<!--通过参数名创建对象-->
<bean id="user" class="com.yin.pojo.User">
<constructor-arg name="name" value="小尹"/>
</bean>
<!-- 比如参数名是name,则有name="具体值" -->
注册bean之后就对象的初始化了(类似 new 类名())
弹幕评论:
-
name方式还需要无参构造和set方法,
-
index和type只需要有参构造
-
就算是new 两个对象,也是只有一个实例(单例模式:全局唯一)
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
system.out.println(user == user2)//结果为true
总结:
在配置文件加载的时候,容器(< bean>)中管理的对象就已经初始化了
spring,我们创建bean的时候,就已经实例化了
5、Spring配置
5.1、别名:alias
<!--通过参数名创建对象-->
<bean id="user" class="com.yin.pojo.User">
<constructor-arg name="name" value="小尹"/>
</bean>
<!--别名,添加了别名可以使用别名,获取这个对象-->
<alias name="user" alias="userNew"/>
<!-- 使用时
User user2 = (User) context.getBean("userNew");
-->
5.2、Bean的配置
<!--别名,添加了别名可以使用别名,获取这个对象-->
<alias name="user" alias="userNew"/>
<!--配置
id:bean的唯一标识符,相当于我们学过的:对象名
class:bean对象所对应权限定名,(报名 + 类型)
name : 别名,name可以同时取多个别名,分隔符可以不同
-->
<bean id="UserT" class="com.yin.pojo.UserT" name="t, t2 t3" >
<property name="name" value="小尹"/>
</bean>
测试
public class MyTest {
public static void main(String[] args) {
//spring这个容器,就类似于婚介网站!
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserT user = (UserT) context.getBean("t3");
user.show();
}
}
=======
UserT被创建了
name:小尹
5.3、import
import一般用于团队开发使用,
它可以将多个配置文件,导入合并为一个
bean的配置无限多
假设,现在项目中有多个人开发,这三个人负责不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的!
-
张三(beans.xm1)
-
李四(beans2.xm1)
-
王五(beans3.xm1)
-
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 https://www.springframework.org/schema/beans/spring-beans.xsd"> <!--导入资源--> <import resource="beans.xml"/> <import resource="beans2.xml"/> <import resource="beans3.xml"/> </beans>
使用的时候,直接使用总的配置就可以了
弹幕评论:
按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个
6、依赖注入(DI)
6.1、构造器注入【核心】
第4点有提到
6.2、set方式注入【核心、重点】
只要用spring,只要有set方法,通过spring都能注入
依赖注入:本质是set注入!
-
依赖:bean对象的创建依赖于容器,
- 我们所有东西都依赖于spring容器做的
-
注入:bean对象中的所有属性,由容器来注入!
【环境搭建】
-
复杂类型
Address类
-
真实测试对象
Student类
-
beans.xml
-
测试
MyTest3
代码实现
Student类
package com.yin.pojo;
import lombok.Getter;
import lombok.Setter;
import java.util.*;
//学生
@Getter
@Setter
public class Student {
private String name;
private Address address;
private String[] book;
private List<String> hobbys; //业余爱好
private Map<String,String> card; //卡片
private Set<String> games; //游戏
private String wife; //妻子
private Properties info; //信息
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", book=" + Arrays.toString(book) +
", hobbys=" + hobbys +
", card=" + card +
", games=" + games +
", wife='" + wife + '\'' +
", info=" + info +
'}';
}
}
Address类
package com.yin.pojo;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
//住址 引用对象
@Getter
@Setter
@ToString
public class Address {
private String address;
}
beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="address" class="com.yin.pojo.Address">
<property name="address" value="山东" />
</bean>
<bean id="student" class="com.yin.pojo.Student">
<!--第一种,普通值注入,直接使用value-->
<property name="name" value="小尹"/>
<!--第二种,bean注入,使用ref注入-->
<property name="address" ref="address"/>
<!--数组注入,-->
<property name="book">
<array>
<value>红楼梦</value>
<value>西游记</value>
<value>水浒传</value>
<value>三国演义</value>
</array>
</property>
<!--list列表注入-->
<property name="hobbys">
<list>
<value>听歌</value>
<value>看电影</value>
<value>敲代码</value>
</list>
</property>
<!--map键值对注入 -->
<property name="card">
<map>
<entry key="身份证" value="111111222222223333"/>
</map>
</property>
<!--set(可去重)注入-->
<property name="games">
<set>
<value>LOL</value>
<value>GTA</value>
</set>
</property>
<!--空指针null注入 -->
<property name="wife" >
<null/>
</property>
<!--properties常量注入 -->
<property name="info">
<props>
<prop key="driver">mysql</prop>
<prop key="url">127.0.0.1</prop>
<prop key="username">root</prop>
<prop key="password">123456</prop>
</props>
</property>
</bean>
</beans>
MyTest3
import com.yin.pojo.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student student = (Student) context.getBean("student");
System.out.println(student.toString());
/*
结果:
Student{name='小尹'
, address='Address(address=山东)'
, book=[红楼梦, 西游记, 水浒传, 三国演义]
, hobbys=[听歌, 看电影, 敲代码]
, card={身份证=111111222222223333}
, games=[LOL, GTA]
, wife='null'
, info={password=123456, url=127.0.0.1, driver=mysql, username=root}
}
*/
}
}
6.3、拓展方式注入
使用p命名空间和c命名空间进行注入
官方文档位置:
代码实现
pojo增加User类
package com.yin.pojo;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
注意: beans 里面加上这下面两行
使用p和c命名空间需要导入xml的头文件约束
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.yin.pojo.User" p:name="小尹" p:age="18" />
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.yin.pojo.User" c:name="小尹" c:age="18" />
</beans>
测试
@Test
public void user(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//确定class对象,就不用再强转了
System.out.println(user);
}
====
User(name=小尹, age=18)
注意
p命名和c命名空间不能直接导入,需要导入xml约束头文件约束
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
6.4、Bean作用域
1.单例模式:(spring的默认机制)
理解
-
singleton,所有东西默认都是单例的
-
创建的所有实例,都只有一个,所有人共享一个对象
-
无论用几个dao去拿都始终用的 accountDao这个实例
-
默认就是单例
-
显示的设置单例
<bean id="user2" class="com.yin.pojo.User" c:name="小尹" c:age="18" scope="singleton"/>
代码实现
实体类
package com.yin.pojo;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
userbeans.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"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.yin.pojo.User" c:name="小尹" c:age="18" scope="singleton"/>
</beans>
测试
@Test
public void user(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//确定class对象,就不用再强转了
User user2 = context.getBean("user2", User.class);//确定class对象,就不用再强转了
System.out.println(user == user2);
}
=======
true
弹幕评论:
- 单例模式是把对象放在pool中,需要再取出来,使用的都是同一个对象实例
2.原型模式:
理解
- 设置了bean为 prototype后,每一个bean创建的都是一个单独的对象
- 每次从容器中get的时候,都产生一个新对象!
- 手动设置
<bean id="user2" class="com.yin.pojo.User" c:name="小尹" c:age="18" scope="prototype"/>
- 浪费资源
代码实现
- 实体类
- userbeans.xml
- 测试
package com.yin.pojo;
import lombok.*;
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!--p命名空间注入,可以直接注入属性的值:property-->
<bean id="user" class="com.yin.pojo.User" p:name="小尹" p:age="18" />
<!--c命名空间注入,通过构造器注入:construct-args-->
<bean id="user2" class="com.yin.pojo.User" c:name="小尹" c:age="18" scope="prototype"/>
</beans>
@Test
public void user(){
ApplicationContext context = new ClassPathXmlApplicationContext("userbeans.xml");
User user = context.getBean("user2", User.class);//确定class对象,就不用再强转了
User user2 = context.getBean("user2", User.class);//确定class对象,就不用再强转了
System.out.println(user == user2);
}
====
1484531981
1159114532
false
说明这两个对象不相等
3.其他
其余的request、session、application这些只能在web开放中使用!
7、Bean的自动装配【重点】
只要名字相同,类型唯一,就能在平时使用,不需要每次都配置
自动装配
-
不设置也能自动找到
-
自动装配是Spring满足bean依赖的一种方式
-
Spring会在上下文自动寻找,并自动给bean装配属性
- 如果名字符合规范的bean,会自动装配上去
- 只需要一个简单的注解:autowire
-
基于上下文,
- 要求:
- 类里边必须要有对应的属性类型
- beans.xml中需要注册
- 要求:
在Spring中有三种装配的方式
- 在xml中显示配置
- 在java中显示配置
- 隐式的自动装配bean 【重要】
7.1、测试:
自动装配,环境搭建:一个人有两个宠物
pojo的Cat类
package com.yin.pojo;
public class Cat {
public void shout(){
System.out.println("喵");
}
}
pojo的Dog类
package com.yin.pojo;
public class Dog {
public void shout(){
System.out.println("汪");
}
}
pojo的People类
package com.yin.pojo;
import lombok.Getter;
import lombok.ToString;
@Getter
@ToString
public class People {
private Cat cat;
private Dog dog;
private String name;
public void setCat(Cat cat) {
this.cat = cat;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public void setName(String name) {
this.name = name;
}
}
配置:beans.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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.yin.pojo.Cat"/>
<bean id="dog" class="com.yin.pojo.Dog"/>
<bean id="people" class="com.yin.pojo.People" >
<property name="name" value="小明"/>
<property name="dog" ref="dog"/>
<property name="cat" ref="cat"/>
</bean>
</beans>
测试
import com.yin.pojo.People;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
People people = context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
}
=========
汪
喵
7.2、byName 自动装配
xml配置 -> byName 自动装配
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.yin.pojo.Cat"/>
<bean id="dog" class="com.yin.pojo.Dog"/>
<bean id="people" class="com.yin.pojo.People" autowire="byName">
<property name="name" value="小明"/>
</bean>
</beans>
原理
byName自动装配:byName会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致
byName会在容器上下文中自动查找,和自己对象set方法的set后面的值对应的id
如果id满足cat或dog,自动装配!
例如:setDog(),取set后面的字符作为id,则要id = dog 才可以进行自动装配
弹幕评论:
byName只能取到小写,大写取不到
弊端:
名字必须唯一,才能自动装配
7.3、byType 自动装配
xml配置 -> byType 自动装配
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="cat" class="com.yin.pojo.Cat"/>
<bean class="com.yin.pojo.Dog"/>
<bean id="people" class="com.yin.pojo.People" autowire="byType">
<property name="name" value="小明"/>
</bean>
</beans>
原理
byType自动装配:byType会自动查找,和自己对象set方法参数的类型相同的bean
byType 会在容器上下文中自动查找,和自己对象属性类型相同的bean
好处:
id可以省略,根据类型来的,所有不需要id也能跑
保证所有的class唯一(类为全局唯一),不需要定义id
弊端:
假设有两个dog就不可以
必须保证类型全局唯一,才能自动装配
<!-- 找不到id和多个相同class -->
<bean id="cat1" class="pojo.Cat"/>
<bean id="cat2" class="pojo.Cat"/>
<!-- 找不到 id=cat,且有两个Cat -->
小结
自动装配的作用
自动装配可以节省很多代码
使用条件,区别:
byName:需要保证所有bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
byType:需要保证所有bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!
7.4、使用注解实现自动装配
jdk1.5支持的注解,spring2.5支持的注解
The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.
(翻译:基于注释的配置的引入提出了一个问题,即这种方法是否比XML“更好”)
使用注解方法
-
导入context约束
- xmlns:context="http://www.springframework.org/schema/context"
-
配置注解的支持:【重要】
- < context:annotation-config/>
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
</beans>
7.4.1、@Autowired(常用)【重点】
默认是byType方式,如果匹配不上,就会byName
在属性上个使用,也可以在set上使用
我们可以不用编写set方法了,前提是自动装配的属性在Spring容器里,且要符合ByName 自动装配
@Getter
@ToString
public class People {
@Autowired//自动导入 开发大量常见
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
在有参构造中设置
@Nullable 字段标记了这个注解,说明该字段可以为空
public name(@Nullable String name){
}
//源码
public @interface Autowired {
boolean required() default true;
}
@Getter
@ToString
public class People {
@Autowired//自动导入 开发大量常见
private Cat cat;
@Autowired(required = false)
private Dog dog;
private String name;
}
如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配,不抛出异常)
7.4.2、@Autowired+@Qualifier
@Autowired不能唯一装配时,需要@Autowired+@Qualifier
如果@Autowired自动装配环境比较复杂。
自动装配无法通过一个注解【 @Autowired】完成的时候,可以使用@Qualifier(value = “xxx”)去配合【 @Autowired】使用,指定一个唯一的id对象注入!
@Getter
@ToString
public class People {
@Autowired//自动导入 开发大量常见
private Cat cat;
@Autowired(required = false)
@Qualifier(value = "dog2")
private Dog dog;
private String name;
}
<!--开启注解的支持-->
<context:annotation-config/>
<bean id="cat" class="com.yin.pojo.Cat"/>
<bean id="dog" class="com.yin.pojo.Dog"/>
<bean id="dog2" class="com.yin.pojo.Dog"/>
<bean id="people" class="com.yin.pojo.People" />
弹幕评论:
如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找
7.4.3、@Resource
默认是byName方式,如果匹配不上,就会byType
@Getter
@ToString
public class People {
@Resource(name = "cat11")
private Cat cat;
@Resource(name = "dog11")
private Dog dog;
private String name;
}
<bean id="cat" class="com.yin.pojo.Cat"/>
<bean id="cat11" class="com.yin.pojo.Cat"/>
<bean id="dog" class="com.yin.pojo.Dog"/>
<bean id="dog11" class="com.yin.pojo.Dog"/>
<bean id="people" class="com.yin.pojo.People" />
弹幕评论:
Autowired是byType,@Autowired+@Qualifier = byType || byName
Autowired是先byteType,如果唯一則注入,否则byName查找。resource是先byname,不符合再继续byType
区别:
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
- 执行顺序不同:
- @Autowired通过byType的方式实现。
- @Resource默认通过byname的方式实现
注解说明
- @Autowired:默认是byType方式,如果匹配不上,就会byName
- 如果@Autowired不能唯一自动装配上属性,则需要通过@Qualifier(value = “XXX”)
- @Nullable 字段标记了这个注解,说明该字段可以为空
- @Resource:默认是byName方式,如果匹配不上,就会byType
8、使用注解开发【掌握】
springboot后全都是注解,看不到配置文件
重点注解:@Autowired、@Component
在spring4之后,使用注解开发,必须要保证aop包的导入
-
spring:注解开发跟简单
- 除了事务,没有什么复杂情况
-
mybatis:建议使用xml配置,能配置复杂情况
-
使用注解需要导入contex的约束
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--注解驱动的支持-->
<context:annotation-config/>
</beans>
8.1、bean注解:@Component【重点】
注解
- component
- 组件,放在类上,说明这个类被spring管理了,bean。
- component:等价于
<bean id="user" class="com.yin.pojo.User"/>
弹幕评论:
有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
在applicationContext.xml中添加
<!--指定要扫描的包,这个包下面的注解才会生效
别只扫一个com.kuang.pojo包-->
<context:component-scan base-package="com.yin.pojo"/>
<context:annotation-config/>
实体类
package com.yin.pojo;
import org.springframework.stereotype.Component;
// @Component(组件) 等价于:<bean id="user" class="com.yin.pojo.User"/>
@Component
public class User {
public String name = "小明";
}
测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
User user = (User) context.getBean("user");
//User user1 = context.getBean("user", User.class);
System.out.println(user.name);
}
}
===
//小明
8.2、属性如何注入@value
package com.yin.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
// @Component(组件) 等价于:<bean id="user" class="com.yin.pojo.User"/>
@Component
public class User {
/*
如何使用?
简单的使用注解,
复杂的使用配置文件,配置文件更快,更清楚
*/
//@Value相当于:<property name="name" value="小尹"/>
//也可以把@Value放在set方法上
public String name;
@Value("小尹")
public void setName(String name) {
this.name = name;
}
}
8.3、@Component衍生的注解
@Component有几个衍生注解,我们在web开发中,会按照mvc架构中分层。
- dao 【@Repository】
- service【@Service】
- controller【@Controller】
这四个注解的功能是一样的,都是代表:将某个类注册到容器(spring)中,装配Bean
8.4、自动装配置
@Autowired:默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
8.5、作用域@scope
平时都用单例模式的
package com.yin.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
// @Component(组件) 等价于:<bean id="user" class="com.yin.pojo.User"/>
@Component
//Scope相当于:<bean scope="prototype"/>
//原型模式prototype,单例模式singleton
@Scope("singleton")
public class User {
//@Value相当于:<property name="name" value="小尹"/>
//也可以把@Value放在set方法上
public String name;
@Value("小尹")
public void setName(String name) {
this.name = name;
}
}
8.6、小结
xml与注解:
- xml:更加万能,维护简单,适用于任何场合
- 注解:
- 不是自己的类使用不了【只能在当前类中使用,局限性】,
- 维护复杂【修改很麻烦】
最佳实践:
-
xml:用来管理bean
-
注解:只用来完成属性的注入
-
理解:bean是纯粹的,bean里边的属性交给注解去完成!
-
在使用的过程中:让注解生效,必须要开启注解支持
-
<!--注解驱动的支持--> <context:annotation-config/> <!--指定要扫描的包,这个包下的注解就会生效--> <context:component-scan base-package="com.yin"/>
-
如何使用?
-
简单的使用注解,
-
复杂的使用配置文件,配置文件更快,更清楚
9、使用Java的方式配置Spring
-
在SpringBoot中常见
-
这种纯java的配置方式 ,在SpringBoot中随处可见
思想
- 不使用Spring的xml配置,完全交给java来做!
javaConfig 是 Spring的一个子项目,在spring4之后,,,它成为了核心功能
注解
-
@Configuration:
- 代表:配置类 ,未来常见
- 【本身就是配置类】也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component,说明做的这些东西都是组件,user、Configuration都是组件
- 代表:这是一个配置类,就和我们之前看到beans.xml是一样的,说明,它可以做beans.xml一样的东西,类似于标签
-
@ComponentScan:
- 扫描包 , 开启扫描
-
@Import:
- 引入其他类
-
@Bean:
- 注册一个bean,就相当于之前写的一个bean标签,
- 方法名 相当于:bean标签的 id属性
- 返回值 相当于:bean标签的 class属性
- return: 返回要注入到bean的对象!
代码实现
ApplicationContext类中:
实体类:pojo的User.java
package com.yin.pojo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/*
@Component注解表明:
一个类会作为组件类,并告知Spring要为这个类创建bean。
这个类被Spring接管了,注册到了容器中 [把User加到容器里边]
*/
@Component
public class User {
private String name;
public String getName() {
return name;
}
@Value("小尹")//属性注入值
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
'}';
}
}
-
弹幕评论:
- 要么使用@Bean,要么使用@Component和ComponentScan,两种效果一样
-
配置文件:config中的kuang.java
-
@Import(KuangConfig2.class),用@import来包含KuangConfig2.java
配置类
package com.yin.config;
import com.yin.pojo.User;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
/**
@Configuration:
【本身就是配置类】也会被Spring容器托管,注册到容器中,因为他本来就是一个@Component,说明做的这些东西都是组件,user、Configuration都是组件
代表:这是一个配置类,就和我们之前看到beans.xml是一样的,说明,它可以做beans.xml一样的东西,类似于<beans>标签
@ComponentScan:
扫描包 , 开启扫描
@Import:
引入其他类
@Bean:
注册一个bean,就相当于之前写的一个bean标签,
方法名 相当于:bean标签的 id属性
返回值 相当于:bean标签的 class属性
return: 返回要注入到bean的对象!
*/
@Configuration
@ComponentScan("com.yin.pojo")
@Import(YinConfig.class)
public class MyConfig {
@Bean
public User getUser(){
return new User();
}
}
- 弹幕评论:
- ComponentScan、@Component("pojo”) 这两个注解配合使用
测试类
public class MyTest {
@Test
public void test(){
//如果完全使用了配置类方式去做,我们就只能通过 AnnotationConfig上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
User getUser = context.getBean("getUser", User.class);//方法名getUser
System.out.println(getUser.getName());
}
}
====
小尹
会创建两个相同对象问题的说明:
弹幕总结 - -> @Bean是相当于< bean>标签创建的对象,而我们之前学的@Component是通过spring自动创建的这个被注解声明的对象,所以这里相当于有两个User对象被创建了。
一个是bean标签创建的(@Bean),一个是通过扫描然后使用@Component,spring自动创建的User对象,所以这里去掉@Bean这些东西,然后开启扫描。之后在User头上用@Component即可达到spring自动创建User对象了
10、动态代理【难点、重点】
代理是帮一些人做一些事情,如:中介
为什么学习代理模式?
- 代理模式是SpringAOP的底层
- 【SpringAOP和SpringMVC面试必问】
代理模式分类:
-
动态代理
-
静态代理
什么是代理模式?
10.1、静态代理
角色分析:
-
抽象角色:
- 他们共同完成的一件事情。如:租房、结婚
- 一般会使用接口或者抽象类来解决。
-
真实角色:
- 被代理的角色
-
代理角色︰
- 代理真实角色,
- 代理真实角色后,我们一般会做一些附属操作
-
客户:
- 访问代理对象的人!
- 用代理对象做一些操作
代码步骤:
- 接口
- 真实角色
- 代理角色
- 客户端访问代理角色
代码实现:
1、接口
package com.yin.demo01;
//租房
public interface Rent {
public void rent();
}
2、真实角色
package com.yin.demo01;
//房东
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要出租房子!");
}
}
3、代理角色
package com.yin.demo01;
/*
中介:代理角色
代理房东,租房子
操作:
1.把房东获取到【原则:先用组合少用继承,继承有局限性】
2.帮房东租房子
看房:
中介能做,房东不能做
中介有套房子,房东只有一套房子
收中介费:
*/
public class Proxy implements Rent{
//组合
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
//帮房东:
@Override
public void rent() {
host.rent();
seeHouse();
fare();
contract();
}
//看房
public void seeHouse(){
System.out.println("中介带你看房 ");
}
//收中介费:
public void fare(){
System.out.println("中介收中介费");
}
//签租赁合同
public void contract(){
System.out.println("签租赁合同");
}
}
4、客户端访问代理角色
package com.yin.demo01;
//我,客户
public class Client {
public static void main(String[] args) {
//房东要租房子
Host host = new Host();
//代理,中介帮房东租房子,但是代理一般会有附属操作:收取一定费用(增加一些房东不做的操作)
Proxy proxy = new Proxy(host);
//你,不用面对房东,直接到中介即可!,但通过代理,还是租到了房子
proxy.rent();
}
}
===
房东要出租房子!
中介带你看房
中介收中介费
签租赁合同
10.2、静态代理模式的好处:
- 可以使真实角色的操作更加纯粹,不用去关注一些公共的业务!
- 公共也就就交给代理角色,实现了业务的分工!
- 公共业务发生扩展的时候,方便集中管理!
缺点:
- 一个真实角色就会产生一个代理角色;
- 代码量会翻倍开发效率会变低
10.3、加深理解
-
实现了业务的分工
-
公共业务发生扩展的时候,方便集中管理!
需求
- 在原有的项目中增加日志
代码步骤
- 业务接口
- 增删改查
- 真实对象
- 实现增删改查
- 代理角色
- 加一个日志方法,没有改变原有的代码
- 客户
代码实现
package com.yin.demo02;
//业务
public interface UserService {
//增删改查
public void add();
public void delete();
public void update();
public void query();
}
package com.yin.demo02;
/*
真实类,真实对象,实现增删改查
需求:
增加一个日志功能
不改变原有的情况下做,加一个代理就可以了
为什么不能再原有的类上添加操作?
1.改动原有的业务代码,在公司中是大忌。
万一改崩了就没了
*/
public class UserServiceImpl implements UserService {
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("修改了一个用户");
}
@Override
public void query() {
System.out.println("查询了一个用户");
}
}
package com.yin.demo02;
/*
代理角色
代理真实角色
需求:打印日志
加一个日志方法,没有改变原有的代码1
*/
public class UserServiceProxy implements UserService{
private UserServiceImpl userService;
//spring注入一个对象,建议使用set方式
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
@Override
public void add() {
log("add");
userService.add();
}
@Override
public void delete() {
log("delete");
userService.delete();
}
@Override
public void update() {
log("update");
userService.update();
}
@Override
public void query() {
log("query");
userService.query();
}
//日志方法
public void log(String msg){
System.out.println("[DeBug]使用了"+msg+"方法");
}
}
package com.yin.demo02;
//客户
public class Client {
public static void main(String[] args) {
//真实角色只做增删改查
UserServiceImpl userService = new UserServiceImpl();
//代理
UserServiceProxy proxy = new UserServiceProxy();
//代理的谁,代理的真实对象
proxy.setUserService(userService);
proxy.add();
}
}
==========
[DeBug]使用了add方法
增加了一个用户
AOP的实现机制
AOP的底层
10.3、动态代理
- 动态代理和静态角色都是一样的,
- 动态代理底层是反射机制
- 动态代理类是动态生成的,不是我们直接写好的!
- 写一个模板,通过模板调用一个接口,自动生成
动态代理(两大类):
- 基于接口:------JDK的动态代理【我们使用这个(默认的)】
- 基于类:-------cglib
- java字节码实现:Javassist
了解两个类
Proxy:代理
-
java.lang.reflect
:反射包下的 -
Proxy
类点击静态方法,能创建一个动态实例
方法
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(),this);
}
InvocationHandler:调用处理程序
java.lang.reflect
:反射包下的InvocationHandler
是由代理实例的调用处理程序实现的接口 。- 由代理实例自动生成一个调用处理程序的接口
- 每个代理实例都有一个关联的调用处理程序。 【代理类】
- 当在代理实例上调用方法时,方法调用将被编码并分派到其调用处理程序的
invoke
方法。invoke
方法:通过反射,执行一个方法
Object invoke(Object proxy, 方法 method, Object[] args);
//参数
//proxy - 调用该方法的代理实例
//method -所述方法对应于调用代理实例上的接口方法的实例。 方法对象的声明类将是该方法声明的接口,它可以是代理类继承该方法的代理接口的超级接口。
//args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。 原始类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean 。
代码实现
接口 Host.java
package com.yin.demo03;
//租房
public interface Rent {
public void rent();
}
接口Host实现类 HostMaster.java
package com.yin.demo03;
//房东
public class Host implements Rent {
@Override
public void rent() {
System.out.println("房东要出租房子!");
}
}
代理角色的处理程序类 ProxyInvocationHandler.java
package com.yin.demo03;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//用这个类,自动生成代理
public class ProxyInvocationHandler implements InvocationHandler {
/* Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),
// new Class<?>[] { Foo.Class },
// handler);*/
//被代理的接口
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成得到代理类[固定代码]
//返回代理类方法
public Object getProxy(){
// newProxyInstance() -> 生成代理对象,就不用再写具体的代理类了
// this.getClass().getClassLoader() -> 找到加载类的位置
// rent.getClass().getInterfaces() -> 代理的具体接口
// this -> 代表了接口InvocationHandler的实现类ProxyInvocationHandler
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
rent.getClass().getInterfaces(), this);
}
//处理代理实例,并返回结果【核心】
//invoke:执行方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
seeHouse();
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(rent, args); //invoke:执行什么方法?接口上的方法
fee();
return result;
}
public void seeHouse(){
System.out.println("中介带看房");
}
public void fee(){
System.out.println("收中介费");
}
}
客户
package com.yin.demo03;
public class Client {
public static void main(String[] args) {
//真实角色
Host host = new Host();
//代理角色:现在没有,只有处理程序,需要通过处理程序生成一个代理类
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//通过调用程序处理角色,来处理我们要调用的接口对象!
//我们所有东西,真实角色和代理角色都会实现同一个接口,现在代理角色没有实现接口
//代理角色,怎么实现接口?通过代理角色的处理程序,来实现。
//pih -> Host接口类 -> Host接口
//调用设置真实代理的角色
pih.setRent(host);
//获取newProxyInstance动态生成代理类,把这个类创建出来
Rent proxy = (Rent) pih.getProxy();//这里的proxy就是动态生成的,我们没有写
//通过代理来调用
proxy.rent();
}
}
弹幕评论:
什么时候调用invoke方法的?
代理实例调用方法时invoke方法就会被调用,可以debug试试
10.4、深化理解
我们来使用动态代理实现代理我们后面写的UserService!
我们也可以编写一个通用的动态代理实现的类!所有的代理对象设置为Object即可!
改为万能代理类
package com.yin.demo04;
import com.yin.demo03.Rent;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//用这个类,自动生成代理 【公式】
public class ProxyInvocationHandler implements InvocationHandler {
/* Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),
// new Class<?>[] { Foo.Class },
// handler);*/
//被代理的接口 :代理谁
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成得到代理类[固定代码]
public Object getProxy(){
// newProxyInstance() -> 生成代理对象,就不用再写具体的代理类了
// this.getClass().getClassLoader() -> 找到加载类的位置
// rent.getClass().getInterfaces() -> 代理的具体接口
// this -> 代表了接口InvocationHandler的实现类ProxyInvocationHandler
return Proxy.newProxyInstance(this.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
//处理代理实例的执行方法,并返回结果【核心】
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
log(method.getName());
//动态代理的本质,就是使用反射机制实现
Object result = method.invoke(target, args); //invoke:执行什么方法?接口上的方法
return result;
}
//日志方法
public void log(String msg){
System.out.println("执行了"+msg+"方法");
}
}
package com.yin.demo04;
import com.yin.demo01.Proxy;
import com.yin.demo02.UserService;
import com.yin.demo02.UserServiceImpl;
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
//代理角色
ProxyInvocationHandler pih = new ProxyInvocationHandler();
//1.代理一个接口,接口是真实对象
pih.setTarget(userService);//设置要代理的对象
//2.动态生成代理类
UserService proxy = (UserService) pih.getProxy();
proxy.delete();
}
}
=====
执行了delete方法
删除了一个用户
10.5、动态代理的好处
静态代理有的它都有,静态代理没有的,它也有!
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
- 公共的业务由代理来完成 . 实现了业务的分工 ,
- 公共业务发生扩展时变得更加集中和方便 .
- 一个动态代理 , 一般代理某一类业务
- 一个动态代理可以代理多个类,代理的是接口
11、AOP【重点】
11.1、什么是AOP
AOP:横向编程的思想,在不影响业务类的情况下,实现动态的增强。
AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。
AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。
利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
11.2、AOP在Spring中的使用
提供声明式事务,允许用户自定义切面
- 横切关注点:跨越应用程序多个模块的方法或功能。即是,与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等…
- 切面(Aspect):横切关注点 被模块化的特殊对象。即,它是一个类。(Log类)
- 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。(Log类中的方法)
- 目标(Target):被通知对象。(生成的代理类)
- 代理(Proxy):向目标对象应用通知之后创建的对象。(生成的代理类)
- 切入点(PointCut):切面通知执行的”地点”的定义。(最后两点:在哪个地方执行,比如:method.invoke())
- 连接点(JointPoint):与切入点匹配的执行点。
- 可以从切入点拿到东西
SpringAOP中,通过Advice定义横切逻辑,Spring中支持5种类型的Advice:
- 可以从切入点拿到东西
即AOP在不改变原有代码的情况下,去增加新的功能。(代理)
11.3、使用Spring实现AOP
【重点】使用AOP,需要导入一个依赖包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
11.3.1、方法一:使用原生spring接口
通过 Spring API 实现
首先编写我们的业务接口和实现类
- UserService.java
package com.yin.service;
//业务
public interface UserService {
public void add();
public void delete();
public void update();
public void select();
}
- UserService 的实现类 UserServiceImp.java
package com.yin.service;
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加了一个用户");
}
@Override
public void delete() {
System.out.println("删除了一个用户");
}
@Override
public void update() {
System.out.println("修改了一个用户");
}
@Override
public void select() {
System.out.println("查询了一个用户");
}
}
然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强
- 前置Log.java
package com.yin.log;
import org.springframework.aop.MethodBeforeAdvice;
import java.lang.reflect.Method;
public class Log implements MethodBeforeAdvice {
//method:要执行的目标对象的方法
//args:参数
//target:目标对象
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(target.getClass().getName() + "的" + method.getName() + "被执行了");
}
}
- 后置AfterLog.java
package com.yin.log;
import org.springframework.aop.AfterReturningAdvice;
import java.lang.reflect.Method;
public class AfterLog implements AfterReturningAdvice {
//returnValue:返回后的,执行后可以拿到返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了" + method.getName()+"方法,返回结果:"+returnValue);
}
}
最后去spring的文件中注册 , 并实现aop切入实现 , 注意导入约束 .
- 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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.yin.service.UserServiceImpl"/>
<bean id="log" class="com.yin.log.Log"/>
<bean id="after" class="com.yin.log.AfterLog"/>
<!--方式一:使用原生的spring API接口
定义一个类,去实现它的接口-->
<!--配置aop,需要导入aop约束-->
<aop:config>
<!--切入点[pointcut]:在那个地方执行spring的方法
expression:表达式, execution(要执行的位置! * xxx修饰符, 返回值, 类名, 方法名, 参数 )
相当于:写一个表达式去定位到这里
*:代表任意的,
com.yin.service.UserServiceImpl:给这个类插入方法
.*: 这个类下的所有方法
(..) :可以有任意参数-->
<aop:pointcut id="pointcut" expression="execution( * com.yin.service.UserServiceImpl.*(..))"/>
<!--执行环绕增加!-->
<!--把log这个类,切入到UserServiceImpl的方法上面-->
<aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
<aop:advisor advice-ref="after" pointcut-ref="pointcut"/>
<!-- 环绕,在id="pointcut"的前后切入 -->
</aop:config>
</beans>
execution(返回类型,类名,方法名(参数)) -> execution(* com.service.,(…))
测试类MyTest5
import com.yin.service.UserService;
import com.yin.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取 ClassPath下的xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理:代理的是接口:注意点
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
=============
com.yin.service.UserServiceImpl的add被执行了
增加了一个用户
执行了add方法,返回结果:null
Spring的Aop就是将公共的业务 (日志 , 安全等) 和领域业务结合起来 , 当执行领域业务时 , 将会把公共业务加进来 . 实现公共业务的重复利用 . 领域业务更纯粹 , 程序猿专注领域业务 , 其本质还是动态代理 .
11.3.2、方法二:自定义类实现AOP
自定义类来实现Aop
【切面定义】
目标业务类不变依旧是userServiceImpl
第一步 : 写我们自己的一个切入类
package com.yin.diy;
//自定义切入点类
public class DiyPointCut {
public void before(){
System.out.println("==========方法执行前============");
}
public void after(){
System.out.println("==========方法执行后============");
}
}
在spring中配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注册bean-->
<bean id="userService" class="com.yin.service.UserServiceImpl"/>
<bean id="log" class="com.yin.log.Log"/>
<bean id="after" class="com.yin.log.AfterLog"/>
<!--方式二:自定义类
用这个类,去执行切入,通过aop来控制-->
<!--注册bean-->
<bean id="diy" class="com.yin.diy.DiyPointCut"/>
<aop:config>
<!--aspect:自定义切面,ref:要引用的类-->
<aop:aspect ref="diy">
<!--把自定义的类,变成切面:三件套-->
<!--切入点-->
<aop:pointcut id="ponit" expression="execution(* com.yin.service.UserServiceImpl.*(..))"/>
<!--通知:一个方法 before, 在ponit执行 -->
<aop:before method="before" pointcut-ref="ponit"/>
<aop:after method="after" pointcut-ref="ponit"/>
</aop:aspect>
</aop:config>
</beans>
测试
import com.yin.service.UserService;
import com.yin.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取 ClassPath下的xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理:代理的是接口:注意点
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
==========方法执行前============
增加了一个用户
==========方法执行后============
11.3.3、方法三:使用注解实现
使用注解实现
第一步:编写一个注解实现的增强类
package com.yin.diy;
//方式三:使用注解方式实现:aop
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect //标注这个类是一个切面
public class AnnotationPointCut {
@Before("execution(* com.yin.service.UserServiceImpl.*(..))")
public void before(){
System.out.println("======方法执行前======");
}
@After("execution(* com.yin.service.UserServiceImpl.*(..))")
public void after(){
System.out.println("======方法执行后======");
}
//在环绕增强中,我们可以给定一个参数,代表我们要获取处理切入的点
@Around("execution(* com.yin.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint jp) throws Throwable {
System.out.println("环绕前");
Object proceed = jp.proceed(); //过滤器,//执行方法
System.out.println("环绕后");
Signature signature = jp.getSignature();//获得签名:类的信息
System.out.println("signature:" + signature);//相当于:toString
// System.out.println(proceed);
}
}
第二步:在Spring配置文件中,注册bean,并增加支持注解的配置
<!--方式三:-->
<!--注册文件-->
<bean id="annotationPointCut" class="com.yin.diy.AnnotationPointCut"/>
<!--开启注解支持,自动代理-->
<!--代理模式两种:
接口:JDK动态代理(默认),expose-proxy="false"
类:cglib,expose-proxy="true" 一般不用
-->
<aop:aspectj-autoproxy expose-proxy="true"/>
测试
import com.yin.service.UserService;
import com.yin.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
//获取 ClassPath下的xml文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//动态代理:代理的是接口:注意点
UserService userService = (UserService) context.getBean("userService");
userService.add();
}
}
=============
环绕前
======方法执行前======
增加了一个用户
======方法执行后======
环绕后
signature:void com.yin.service.UserService.add()
12、整合mybatis【重要】
步骤:
-
导入相关jar包
-
junit
-
mybatis
-
MySQL数据库
-
spring相关的
-
aop织入
-
mybatis-spring【new知识点】
- 专门整合spring和mybatis的
-
lombok
-
配置Maven静态资源过滤问题!
-
<!--配置Maven静态资源过滤问题!--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
-
-
<dependencies> <!--junit--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <!--spring相关的包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.2.7.RELEASE</version> </dependency> <!--spring操作数据库,需要spring-jdbc包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.10.RELEASE</version> </dependency> <!--aspectJ AOP 织入器--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency> <!--mybatis-spring整合包 【重点】--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency> </dependencies>
-
-
编写配置文件
-
测试
12.1、回忆MyBatis
mybatis的配置流程:
1.编写实体类
User
package com.yin.pojo;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private String pwd;
}
2.编写核心配置文件
mybatis-config.xml
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--别名-->
<typeAliases>
<package name="com.yin.pojo"/>
</typeAliases>
<!--mybatis的数据源-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT "/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--最核心的-->
<mappers>
<mapper class="com.yin.mapper.UserMapper"/>
</mappers>
</configuration>
3.编写接口
UserMapper
public interface UserMapper {
public List<User> selectUser();
}
4.编写Mapper.xml
UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--绑定的接口-->
<mapper namespace="com.yin.mapper.UserMapper">
<select id="selectUser" resultType="user">
select *
from user ;
</select>
</mapper>
5.测试
MyTest
public class MyTest {
@Test
public void test() throws IOException {
//加载配置文件
String resources = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resources);
//通过 Builder 把流加载进来
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//用sessionFactory创建openSession 自动提交事务
SqlSession sqlSession = sessionFactory.openSession(true);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}
==========
User(id=1, name=张三, pwd=123)
User(id=2, name=AAA, pwd=BBB)
User(id=3, name=小明, pwd=123)
User(id=6, name=小花, pwd=123)
注意点
- xml导入不成功,解决办法:配置Maven静态资源过滤问题!
- 1 字节的 UTF-8 序列的字节 1 无效。解决办法:在xml中把UTF-8改为UTF8
12.2、MyBatis-Spring学习
引入Spring之前需要了解mybatis-spring包中的一些重要类;
什么是 MyBatis-Spring?
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。
知识基础
在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要
MyBatis-Spring 需要以下版本:
MyBatis-Spring | MyBatis | Spring 框架 | Spring Batch | Java |
---|---|---|---|---|
2.0 | 3.5+ | 5.0+ | 4.0+ | Java 8+ |
1.3 | 3.4+ | 3.2.2+ | 2.1+ | Java 6+ |
入门
安装
如果使用 Maven 作为构建工具,仅需要在 pom.xml 中加入以下代码即可:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
快速上手
要和 Spring 一起使用 MyBatis,需要在 Spring 应用上下文中定义至少两样东西:【这些东西原来都是mybatis配置死的】
- 一个
SqlSessionFactory
- 至少一个数据映射器类
在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean
来创建 SqlSessionFactory
。 要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中:
SqlSessionFactory:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
注意:SqlSessionFactory
需要一个 DataSource
(数据源)。 这可以是任意的 DataSource
,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder
来创建 SqlSessionFactory
的。 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean
来创建。
在 MyBatis 中,你可以使用 SqlSessionFactory
来创建 SqlSession
。一旦你获得一个 session 之后,你可以使用它来执行映射了的语句,提交或回滚连接,最后,当不再需要它的时候,你可以关闭 session。
SqlSessionFactory
有一个唯一的必要属性:用于 JDBC 的 DataSource
。这可以是任意的 DataSource
对象,它的配置方法和其它 Spring 数据库连接是一样的。
一个常用的属性是 configLocation
,它用来指定 MyBatis 的 XML 配置文件路径。它在需要修改 MyBatis 的基础配置非常有用。通常,基础配置指的是 <settings>
或 <typeAliases>
元素。
需要注意的是,这个配置文件并不需要是一个完整的 MyBatis 配置。确切地说,任何环境配置(<environments>
),数据源(<DataSource>
)和 MyBatis 的事务管理器(<transactionManager>
)都会被忽略。SqlSessionFactoryBean
会创建它自有的 MyBatis 环境配置(Environment
),并按要求设置自定义环境的值。
SqlSessionTemplate
是 MyBatis-Spring 的核心。作为 SqlSession
的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession
。
模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate
来替换 MyBatis 默认的 DefaultSqlSession
实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。
可以使用 SqlSessionFactory
作为构造方法的参数来创建 SqlSessionTemplate
对象。
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
现在,这个 bean 就可以直接注入到你的 DAO bean 中了。你需要在你的 bean 中添加一个 SqlSession 属性,就像下面这样:
public class UserDaoImpl implements UserDao {
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public User getUser(String userId) {
return sqlSession.getMapper...;
}
}
按下面这样,注入 SqlSessionTemplate
:
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
<property name="sqlSession" ref="sqlSession" />
</bean>
12.3、整合实现一【掌握】
手动注入:
SqlSessionTemplate
比较重要
- 理解了这个,才能理解原来的mybatis怎么一对一
- 公司常用mybatis-plus:用插件做,不需要增删改查。通用mapper
SqlSessionTemplate
是 MyBatis-Spring 的核心。
- 可以完全替代SqlSession
思路:
步骤
- 编写数据源配置
- sqISessionFactory
- sqISessionTemplate(相当于sqISession)
- 需要给接口加实现类【new】
- 将自己写的实现类,注入到Spring中
- 测试!
项目结构
编写顺序:
-
User ------> 编写数据库实体类
-
UserMapper ------> 编写UserMapper接口
-
UserMapper.xml ------> 编写UserMapper.xml配置文件
- 绑定接口,写sql语句
-
mybatis-config.xml ------> mybatis配置文件
- 设置(日志)、别名
-
spring-dao.xml ------> spring操作数据库的配置文件
- DataSource【数据源】
- 配置sqlSessionFactory 对象 【核心对象 】
- 创建sqlSession 对象【核心对象 】
-
UserServiceImpl ------> 实现类
- 这个实现类的方法去操作原来mybatis在测试类中做的事情
- 获得SqlSession对象
- 执行SQL,调用UserMapper对象,通过getMapper方式
- 实现类作用
- 把SqlSession私有了,通过SqlSessionTemplate注入进去
- 这个实现类的方法去操作原来mybatis在测试类中做的事情
-
applicationContext.xml ------> 配置文件
- 调用:spring-dao.xml配置文件
- 把实现类 UserMapperImpl 注入到spring里
- 使用方法:spring里边调用userMapper,调它的方法
-
MyTest6
- 调用UserMapperImpl实现类, 在applicationContext.xml中是 userMapper
代码步骤:
-
引入Spring配置文件:spring-dao.xml
- 需要做两件事:配置数据源、配置SqlSessionFactory
<?xml version="1.0" encoding="UTF8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> </beans>
-
配置数据源,替换mybatis-config.xml中的mybatis的数据源【spring管理数据源】
<!--配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的--> <!--DataSource【数据源】: 使用Spring的数据源替换mybatis的配置 也可以用其他的:c3p0、dbcp、druid class中的类,我们使用spring提供的jdbc: - DriverManagerDataSource:驱动管理数据源 - org.springframework.jdbc.datasource:引入这个依赖 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
-
这里把数据源搞定了,就可以省略掉:mybatis-config.xml配置文件中的数据源
-
<!--mybatis的数据源--> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT "/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments>
-
-
-
配置SqlSessionFactory,关联MyBatis
使用步骤:
- 注入一个数据源:dataSource
- 绑定mybatis的配置文件,最后测试的是spring,不绑定用不了
<!--sqlSessionFactory 对象 (工厂模式,生成产品的) 生成的产品:sqlSession 帮我们处理:sqlSessionFactory的创建 sqlSessionFactory:使用步骤: 1.注入一个数据源:dataSource 2.绑定mybatis的配置文件,最后测试的是spring,不绑定用不了 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--绑定mybatis配置文件 configLocation: mybatis配置文件地址 classpath:mybatis-config.xml: 这样可以在mybatis-config.xml中扩展,这两个相连了 mapperLocations: 注册映射器 --> <!--关联Mybatis:绑定的地址,classpath:mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <property name="mapperLocations" value="classpath:com/yin/mapper/*.xml"/> </bean>
-
这里配置了SqlSessionFactory,数据源有了,dataSource有了,就可以帮我们处理SqlSessionFactory的创建,
-
测试代码类中的SqlSessionFactory 创建就不需要了
-
//加载配置文件 String resources = "mybatis-config.xml"; // 读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resources); //通过 Builder 把流加载进来 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
-
-
绑定mybatis配置文件,可以省略在mybatis中配置,如下
-
<property name="mapperLocations" value="classpath:com/yin/mapper/*.xml"/>
-
<!--最核心的 注册映射器--> <mappers> <mapper class="com.yin.mapper.UserMapper"/> </mappers>
-
-
一般情况下在mybatis配置文件中里留下两项:设置、别名
-
<?xml version="1.0" encoding="utf8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 一般情况下在mybatis里留下两项: 别名管理 设置: 把日志开启等,放到这里设置 --> <!--设置--> <settings> <setting name="logImpl" value="STDOUT_LOGGING" /> </settings> <!--别名--> <typeAliases> <package name="com.yin.pojo"/> </typeAliases> </configuration>
-
-
创建:SqlSession对象
使用步骤:
- 通过SqlSessionTemplate生成sqlSession
- 通过唯一的构造方法,把sqlSessionFactory拿进来
<!--创建:SqlSession对象 以后遇到:XXXTemplate:模板,redisTemplate、thymeTemplate SqlSessionTemplate: 就是我们使用的sqlSession SqlSessionTemplate使用: 1.通过SqlSessionTemplate生成sqlSession 2.通过唯一的构造方法,把sqlSessionFactory拿进来 --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--报错:没有注入参数,没有set方法,只能使用,构造方法注入:有三种方式--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
spring绑定后,加一个实现类,
UserMapper.xml是写sql语句的,真正执行的由于SqlSessionFactory变成了面向对象的 ,需要一个实现类:UserMapperImpl
实现类作用:
- 把SqlSession私有了,通过SqlSessionTemplate注入进去
public class UserMapperImpl implements UserMapper{ /* 多加了一个实现类 好处:new 这个类就可以直接调用。 前提是在这里需要注入东西,把sqlSession注入进来,用set方法注入【spring万物皆注入】 在原来,我们的所有操作都使用sqlSession来执行,现在,都使用SqlSessionTemplate ,他们两个是一个东西 理解: 刚才所有的东西都在测试类中写的,现在spring整合mybatis 在类里边操作,调用这个类的方法就好了。把这个实现类注入到spring里 为什么多一个实现类? 因为spring需要接管这个对象spring自动创建,mybatis不能自动创建,只能手动写set方法,这个set方法来做原来mybatis做的事情,把它作为业务类来做 */ private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; } @Override public List<User> selectUser() { UserMapper mapper = sqlSession.getMapper(UserMapper.class); return mapper.selectUser(); } }
- 以前:所有的东西都在测试类中完成,现在:spring整合mybatis后,在类里边操作,调用类的方法即可
-
把实现类 UserMapperImpl 注入到spring里
为了分工明确,创建一个applicationContext.xml
-
applicationContext.xml,里只负责:注册bean,调用spring-dao.xml。
-
spring-dao.xml,里负责 :操作数据库,这里边的代码不需要改动。
-
之后学习MVC,在写个
<import resource="spring-mvc.xml"/>
,专注于做MVC即可
<?xml version="1.0" encoding="UTF8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--调用--> <import resource="spring-dao.xml"/> <!--把实现类 UserMapperImpl 注入到spring里 现在的使用方法:spring里边调用userMapper,调它的方法 --> <bean id="userMapper" class="com.yin.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> </beans>
-
现在不需要测试类中的代码了,mybatis抛弃了,mybatis被我们内部集成了,再也不需要写他的东西了
-
抛弃的MyTest:测试代码;
-
UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.selectUser(); for (User user : userList) { System.out.println(user); }
-
-
-
测试
public class MyTest { @Test public void test() throws IOException { /* 思路: 现在整合mybatis后,连接数据库,业务很纯粹,测试类做自己只做自己的事: userMapper,userMapper能调用selectUser(), 它的实现,原来:放在service业务层去做的, 现在:spring整合之后,在实现类中定义,这个实现类的方法去操作原来mybatis在测试类中做的事情 */ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //真正执行:调用UserMapperImpl实现类, 在applicationContext.xml中是 userMapper UserMapper userMapper = context.getBean("userMapper", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); } } }
-
环境中,mybatis彻底不见了
-
输出结果:
-
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3754a4bf] was not registered for synchronization because synchronization is not active JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@13fd2ccd] will not be managed by Spring ==> Preparing: select * from user ; ==> Parameters: <== Columns: id, name, pwd <== Row: 1, 张三, 123 <== Row: 2, AAA, BBB <== Row: 3, 小明, 123 <== Row: 6, 小花, 123 <== Total: 4 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3754a4bf] User(id=1, name=张三, pwd=123) User(id=2, name=AAA, pwd=BBB) User(id=3, name=小明, pwd=123) User(id=6, name=小花, pwd=123)
-
-
12.3、整合实现二【了解】
mybatis-spring1.2.3版以上的才有这个
官方文档截图 :
dao继承Support类 ,,直接利用 getSqlSession()
获得 , 然后直接注入SqlSessionFactory .
比起方式1 , 不需要管理SqlSessionTemplate ,而且对事务的支持更加友好 . 可跟踪源码查看
代码步骤:
-
创建UserMapperImpl2对象
package com.yin.mapper; import com.yin.pojo.User; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> selectUser() { //getSqlSession是继承的类写的 //SqlSession sqlSession = getSqlSession(); //UserMapper mapper = sqlSession.getMapper(UserMapper.class); //精简成一行 return getSqlSession().getMapper(UserMapper.class).selectUser(); } }
-
用这种方式去继承了,方式一中的注入的过程可以省略了,省略的代码
-
private SqlSessionTemplate sqlSession; public void setSqlSession(SqlSessionTemplate sqlSession) { this.sqlSession = sqlSession; }
-
-
-
写完一个类,用了spring,把这个类配到spring里
<?xml version="1.0" encoding="UTF8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"> <!--调用--> <import resource="spring-dao.xml"/> <!--方式一--> <bean id="userMapper" class="com.yin.mapper.UserMapperImpl"> <property name="sqlSession" ref="sqlSession"/> </bean> <!--方式二--> <bean id="userMapper2" class="com.yin.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> </beans>
-
方式二中没有属性,需要注入sqlSessionFactory,少了一步。
-
UserMapperImpl2不需要注入,但是它的父类需要sqlSessionFactory,
-
方式一中注入了sqlSession,这个sqlSession是在之前我们在spring-dao.xml配置的sqlSession,
-
如果用了方式二,可以省略:SqlSession对象的创建,只需要配置:数据源和sqlSessionFactory
-
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--报错:没有注入参数,没有set方法,只能使用,构造方法注入:有三种方式--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
-
-
测试
@Test public void test() throws IOException { /* 思路: 现在整合mybatis后,连接数据库,业务很纯粹,测试类做自己只做自己的事: userMapper,userMapper能调用selectUser(), 它的实现,原来:放在service业务层去做的,现在:spring整合之后,在实现类中定义,这个实现类的方法去操作原来mybatis在测试类中做的事情 */ ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //真正执行:调用UserMapperImpl实现类, 在applicationContext.xml中是 userMapper UserMapper userMapper = context.getBean("userMapper2", UserMapper.class); List<User> userList = userMapper.selectUser(); for (User user : userList) { System.out.println(user); }
-
输出结果
-
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@75d4a5c2] was not registered for synchronization because synchronization is not active JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@7db12bb6] will not be managed by Spring ==> Preparing: select * from user ; ==> Parameters: <== Columns: id, name, pwd <== Row: 1, 张三, 123 <== Row: 2, AAA, BBB <== Row: 3, 小明, 123 <== Row: 6, 小花, 123 <== Total: 4 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@75d4a5c2] User(id=1, name=张三, pwd=123) User(id=2, name=AAA, pwd=BBB) User(id=3, name=小明, pwd=123) User(id=6, name=小花, pwd=123)
-
总结 :
整合到spring中以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现,这个等我们后面学习SpringBoot的时候还会测试整合!
13、声明式事务
13.1、回顾事务
- 事务特性:把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务的ACID原则:
-
原子性
- 确保这个东西,要么都成功,要么都失败!
-
一致性
- 一旦事务完成,要么都提交,要么不提交,保持资源一致。
-
隔离性
- 多个业务可能操作同一个资源,保证多个业务操作同一个资源相互隔离,不会影响数据的正确性。【防止数据损坏】
- 防止数据损坏:确保完整性和一致性
-
持久性
- 事务一旦提交,无论系统发生什么问题,结果都不会被影响,被持久化的写到存储器中(存储器不一定是事务)。
13.2、测试
步骤
1、整合mybatis步骤
-
导入依赖
-
建包、建类
- pojo—User
- UserMapper
-
用mybatis,导入mybatis的配置
- mybatis-config.xml
-
整合mybatis配置文件
- spring-dao.xml
-
接口实现类,操作数据库的实现类,sql语句,拿来用。这里整合mybatis就好了,但是还无法使用,需要实现类
- UserMapper.xml
-
实现类,有两种方式
- UserMapperImpl
-
需要把实体类注入到spring里,需要一个spring配置文件:
- applicationContext.xml
-
测试
2、代码实现
导入依赖
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--spring相关的包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<!--spring操作数据库,需要spring-jdbc包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>
<!--aspectJ AOP 织入器-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<!--mybatis-spring整合包 【重点】-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
</dependencies>
<!--在build中配置resources,来防止资源导出失败的问题-->
<!--配置Maven静态资源过滤问题!-->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
建包、建类
pojo User实体类
package com.yin.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//getset
@AllArgsConstructor//有参
@NoArgsConstructor//无参
public class User {
private int id;
private String name;
private String pwd;
}
UserMapper接口
package com.yin.mapper;
import com.yin.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
mybatis的配置
mybatis-config.xml
<?xml version="1.0" encoding="utf8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--
一般情况下在mybatis里留下两项:
别名管理
设置: 把日志开启等,放到这里设置
-->
<!--设置-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<!--别名-->
<typeAliases>
<package name="com.yin.pojo"/>
</typeAliases>
</configuration>
整合mybatis配置文件
spring-dao.xml
<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--=================操作数据库======================-->
<!--配置数据源:数据源有非常多,可以使用第三方的,也可使使用Spring的-->
<!--DataSource【数据源】:
使用Spring的数据源替换mybatis的配置 也可以用其他的:c3p0、dbcp、druid
class:中的类,我们使用spring提供的jdbc
DriverManagerDataSource:驱动管理数据源
org.springframework.jdbc.datasource:引入这个依赖
-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--=================核心的对象:sqlSessionFactory、SqlSessionTemplate=========================-->
<!--sqlSessionFactory 对象 (工厂模式,生成产品的) 生成的产品:sqlSession
帮我们处理:sqlSessionFactory的创建
sqlSessionFactory:使用步骤:
1.注入一个数据源:dataSource
2.绑定mybatis的配置文件,最后测试的是spring,不绑定用不了
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--绑定mybatis配置文件
configLocation: mybatis配置文件地址
classpath:mybatis-config.xml: 这样可以在mybatis-config.xml中扩展,这两个相连了
mapperLocations: 注册映射器
-->
<!--关联Mybatis-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:com/yin/mapper/*.xml"/>
</bean>
<!--创建:SqlSession对象
以后遇到:XXXTemplate:模板,redisTemplate、thymeTemplate
SqlSessionTemplate: 就是我们使用的sqlSession
SqlSessionTemplate使用:
1.通过SqlSessionTemplate生成sqlSession
2.通过唯一的构造方法,把sqlSessionFactory拿进来
-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--报错:没有注入参数,没有set方法,只能使用,构造方法注入:有三种方式-->
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
</beans>
操作数据库的Mapper.xml
UserMapper.xml配置文件
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--绑定的接口-->
<mapper namespace="com.yin.mapper.UserMapper">
<select id="selectUser" resultType="user">
select *
from user ;
</select>
</mapper>
实现类
UserMapperImpl
package com.yin.mapper;
import com.yin.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
spring配置文件
applicationContext.xml
<?xml version="1.0" encoding="UTF8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<import resource="spring-dao.xml"/>
<!--配置bean-->
<bean id="userMapper" class="com.yin.mapper.UserMapperImpl">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
</beans>
测试
import com.yin.mapper.UserMapper;
import com.yin.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
输出结果
Checking to see if class com.yin.pojo.User matches criteria [is assignable to Object]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15c43bd9] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@e7edb54] will not be managed by Spring
==> Preparing: select * from user ;
==> Parameters:
<== Columns: id, name, pwd
<== Row: 1, 张三, 123
<== Row: 2, AAA, BBB
<== Row: 3, 小明, 123
<== Row: 6, 小花, 123
<== Total: 4
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@15c43bd9]
User(id=1, name=张三, pwd=123)
User(id=2, name=AAA, pwd=BBB)
User(id=3, name=小明, pwd=123)
User(id=6, name=小花, pwd=123)
3、模拟事务失败步骤
- 在UserMapper中添加一组业务
- 在UserMapper.xml中写sql
- 在UserMapperImpl中补全代码
- 测试
4、事务失败代码
UserMapper
package com.yin.mapper;
import com.yin.pojo.User;
import org.apache.ibatis.annotations.Param;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
//添加一个用户
public int addUser(User user);
//删除一个用户
public int deleteUser( int id);
}
UserMapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--绑定的接口-->
<mapper namespace="com.yin.mapper.UserMapper">
<select id="selectUser" resultType="user">
select *
from user ;
</select>
<insert id="addUser" parameterType="user">
insert into user (id, name, pwd)
values (#{id}, #{name},#{pwd});
</insert>
<!--为了出错,查看事务-->
<delete id="deleteUser" parameterType="int">
deletes
from user
where id = #{id};
</delete>
</mapper>
UserMapperImpl
package com.yin.mapper;
import com.yin.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper{
@Override
public List<User> selectUser() {
//变成一组事务
User user = new User(5, "小王", "13123");
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
//把user添加进去
mapper.addUser(user);
mapper.deleteUser(5);
return mapper.selectUser();
}
@Override
public int addUser(User user) {
return getSqlSession().getMapper(UserMapper.class).addUser(user);
}
//这里执行会出错
@Override
public int deleteUser(int id) {
return getSqlSession().getMapper(UserMapper.class).deleteUser(id);
}
}
测试
import com.yin.mapper.UserMapper;
import com.yin.pojo.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
//执行这个方法的时候,插入一条数据
List<User> userList = userMapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}
=======================
输出结果:
Checking to see if class com.yin.pojo.User matches criteria [is assignable to Object]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c407114] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@79da8dc5] will not be managed by Spring
==> Preparing: insert into user (id, name, pwd) values (?, ?,?);
==> Parameters: 5(Integer), 小王(String), 13123(String)
<== Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3c407114]
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@24fcf36f] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@3fb1549b] will not be managed by Spring
==> Preparing: deletes from user where id = ?;
==> Parameters: 5(Integer)
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@24fcf36f]
异常:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'deletes
结论
五号数据被插入进去了,这样不符合原则
应该让这一组事务要么都成功,要么都失败
- 原来:事务可以,如果出现异常可以try catch回滚,现在:这个异常无法捕获
- 解决办法:要么改变原来的类,要么使用横切AOP,一个事务去实现。
总结
报错:sql异常,delete写错了
结果 :插入成功!
没有进行事务的管理;我们想让他们都成功才成功,有一个失败,就都失败,我们就应该需要事务!
以前我们都需要自己手动管理事务,十分麻烦!
但是Spring给我们提供了事务管理,我们只需要配置即可;
13.3、Spring中的事务管理
分为两类
- 声明式事务:
- AOP的应用,代码是横切进去的,不影响代码。
- 一般情况下都使用AOP方式做
- 编程式事务:
- 需要在代码中,进行事务管理。
Spring在不同的事务管理API之上定义了一个抽象层,使得开发人员不必了解底层的事务管理API就可以使用Spring的事务管理机制。Spring支持编程式事务管理和声明式的事务管理。
编程式事务管理
- 将事务管理代码嵌到业务方法中来控制事务的提交和回滚
- 缺点:必须在每个事务操作业务逻辑中包含额外的事务管理代码
声明式事务管理
- 一般情况下比编程式事务好用。
- 将事务管理代码从业务方法中分离出来,以声明的方式来实现事务管理。
- 将事务管理作为横切关注点,通过aop方法模块化。Spring中通过Spring AOP框架支持声明式事务管理。
使用Spring管理事务,注意头文件的约束导入 : tx
代码优化
优化:当执行失败时,不能被插入数据
优化步骤
-
在spring-dao.xml中配置声明式事务,开启 Spring 的事务处理功能
-
在spring-dao.xml中,结合AOP实现事务的织入
-
测试
-
查看结果
-
把代码修改正确,再次测试并查看结果
代码实现
- 在spring-dao.xml中配置声明式事务,开启 Spring 的事务处理功能
<!--
配置声明式事务
开启 Spring 的事务处理功能-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
- 在spring-dao.xml中,结合AOP实现事务的织入
- 死代码,只需要修改切入点即可
<!--2.结合AOP实现事务的织入
执行增删改查方法的时候,自动去往里边丢事务-->
<!--2.1、配置事务通知,spring帮我们做了.tx:事务-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--给那些方法配置事务:add……
配置事务的传播特性:new
propagation="REQUIRED",默认的 。开启事务支持
read-only="true" : query带头的不能进行增删改的操作-->
<tx:attributes>
<tx:method name="add" propagation="REQUIRED"/>
<tx:method name="delete" propagation="REQUIRED"/>
<tx:method name="update" propagation="REQUIRED"/>
<tx:method name="query" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!--2.2、配置事务切入-->
<aop:config>
<!--事务的切入点, mapper下的所有类下的所有切入点-->
<aop:pointcut id="txPointCut" expression="execution(* com.yin.mapper.*.*(..))"/>
<!--切入: 把txAdvice事务切入到 txPointCut,现在这个包下的所有方法都会被编制上事务 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
- 测试
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
//执行这个方法的时候,插入一条数据
List<User> userList = userMapper.selectUser();
for (User user : userList) {
System.out.println(user);
}
}
}
- 结果
- 数据库中没有五号用户,说明事务失败了
- 数据库中没有五号用户,说明事务失败了
- 再次测试,查看结果
- 在UserMapperImpl类中,修改删除的用户,就能看到插入的用户了
- 成功运行,说明事务插入成功了
User(id=1, name=张三, pwd=123)
User(id=2, name=AAA, pwd=BBB)
User(id=3, name=小明, pwd=123)
User(id=5, name=小王, pwd=13123)
思考
为什么需要事务?保证事务的ACID原则。
- 如果不配置事务,可能存在数据提交不一致的情况下;
- 如果不在spring中去配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中非常重要,涉及到数据的一致性和完整性问题!
学习思路
先看代码,代码能看得懂,不需要回看视频
可以把所有的代码,都修改成javaconfig
掌握:动态代理,多去看反射!
整合mybatis重要,不会多练几遍
声明式事务,会用就好,配置是固定的
注意点
要用织入必须导入包
<!--aspectJ AOP 织入器-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
要用spring的事务管理器,导入包
<!--spring操作数据库,需要spring-jdbc包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.10.RELEASE</version>
</dependency>