(转载)【狂神说Java】Spring5笔记存档
转载于 https://www.cnblogs.com/melodyjerry/p/13549091.html
视频:https://www.bilibili.com/video/BV1WE411d7Dv
1、Spring
1.1、简介
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最新版
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
<!-- 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、组成
1.4、扩展
现代化的java开发 -> 基于Spring的开发
2、IOC理论推导
传统的调用
-
UserDao
复制代码- 1
- 2
- 3
- 4
javapackage dao; public interface UserDao { void getUser(); } -
UserDaoImp
复制代码- 1
- 2
- 3
- 4
- 5
- 6
javapackage dao; public class UserDaoImpl implements UserDao{ public void getUser() { System.out.println("默认获取用户数据"); } } -
UserSevice
复制代码- 1
- 2
- 3
- 4
javapackage Service; public interface UserService { void getUser(); } -
UserServiceImp
复制代码- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
javapackage Service; import dao.UserDao; import dao.UserDaoImpl;public class UserServiceImpl implements UserService{
UserDao userDao = new UserDaoImpl();
public void getUser(){
userDao.getUser();
}
}
测试
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
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接口实现。已经发生了革命性的变化!
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
//在Service层的实现类(UserServiceImpl)增加一个Set()方法
//利用set动态实现值的注入!
private UserDao userDao;
public void setUserDao(UserDao userDao){
this.userDao = userDao;
}
set() 方法实际上是动态改变了 UserDao userDao 的 初始化部分(new UserDaoImpl())
测试中加上
复制代码
- 1
((UserServiceImpl)userService).setUserDao(new UserDaoImpl());
- 之前,程序是主动创建对象!控制权在程序猿手上!
- 使用了set注入后,程序不再具有主动性,而是变成了被动的接受对象!(主动权在客户手上)
本质上解决了问题,程序员不用再去管理对象的创建
系统的耦合性大大降低,可以更专注在业务的实现上
这是IOC(控制反转)的原型,反转(理解):主动权交给了用户
IOC本质
3、HolleSpring
在父模块中导入jar包
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
<!-- 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
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
package pojo;
public class Hello {
<span class="hljs-keyword">private</span> String str;
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getStr</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> str;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setStr</span><span class="hljs-params">(String str)</span> </span>{
<span class="hljs-keyword">this</span>.str = str;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"Holle [str="</span> + str + <span class="hljs-string">"]"</span>;
}
}
在resource里面的xml配置
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
<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">
<span class="hljs-comment"><!--在Spring中创建对象,在Spring这些都称为bean
类型 变量名 = new 类型();
Holle holle = new Holle();
bean = 对象(holle)
id = 变量名(holle)
class = new的对象(new Holle();)
property 相当于给对象中的属性设值,让str="Spring"
--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"hello"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.Hello"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"str"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"Spring"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
测试类MyTest
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
package holle1;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Hello;
public class MyTest {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-comment">//获取Spring的上下文对象</span>
ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">"beans.xml"</span>);
<span class="hljs-comment">//我们的对象下能在都在spring·中管理了,我们要使用,直接取出来就可以了</span>
Hello holle = (Hello) context.getBean(<span class="hljs-string">"hello"</span>);
System.out.println(holle.toString());
}
}
核心用set注入,所以必须要有下面的se()方法
复制代码
- 1
- 2
- 3
- 4
//Hello类
public void setStr(String str) {
this.str = str;
}
思考:
IOC:对象由Spring 来创建,管理,装配!
弹幕评论里面的理解:
原来这套程序是:你写好菜单买好菜,客人来了自己把菜炒好招待,就相当于你请人吃饭
现在这套程序是:你告诉楼下餐厅,你要哪些菜,客人来的时候,餐厅把做好的你需要的菜送上来
IoC:炒菜这件事,不再由你自己来做,而是委托给了第三方__餐厅来做
此时的区别就是,如果我还需要做其他的菜,我不需要自己搞菜谱买材料再做好,而是告诉餐厅,我要什么菜,什么时候要,你做好送来
.
在前面第一个module试试引入Spring
复制代码
- 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id=<span class="hljs-string">"userDaomSql"</span> <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"dao.UserDaoMysqlImpl"</span>></bean>
<bean id=<span class="hljs-string">"userServiceImpl"</span> <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"service.UserServiceImp"</span>>
<!--ref引用spring中已经创建很好的对象-->
<!--value是一个具体的值,基本数据类型-->
<property name=<span class="hljs-string">"userDao"</span> ref=<span class="hljs-string">"userDaomSql"</span>/>
</bean>
</beans>
第一个module改良后测试
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
package holle0;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserServiceImpl;
public class MyTest0 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserServiceImpl userServiceImpl = (UserServiceImpl) context.getBean("userServiceImpl");
userServiceImpl.getUser();
}
}
总结:
所有的类都要装配的beans.xml 里面;
所有的bean 都要通过容器去取;
容器里面取得的bean,拿出来就是一个对象,用对象调用方法即可;
4、IOC创建对象的方式
- 使用无参构造创建对象,默认。
- 使用有参构造(如下)
下标赋值
index指的是有参构造中参数的下标,下标从0开始;
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
<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">
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.User"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">index</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"chen"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
类型赋值(不建议使用)
复制代码
- 1
- 2
- 3
<bean id="user" class="pojo.User">
<constructor-arg type="java.lang.String" value="kuang"/>
</bean>
直接通过参数名(掌握)
复制代码
- 1
- 2
- 3
- 4
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="kuang"></constructor-arg>
</bean>
<!-- 比如参数名是name,则有name="具体值" -->
注册bean之后就对象的初始化了(类似 new 类名())
弹幕评论:
name方式还需要无参构造和set方法,index和type只需要有参构造
就算是new 两个对象,也是只有一个实例(单例模式:全局唯一)
复制代码
- 1
- 2
- 3
User user = (User) context.getBean("user");
User user2 = (User) context.getBean("user");
system.out.println(user == user2)//结果为true
总结:在配置文件加载的时候,容器(< bean>)中管理的对象就已经初始化了
5、Spring配置
5.1、别名
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
<bean id="user" class="pojo.User">
<constructor-arg name="name" value="chen"></constructor-arg>
</bean>
<alias name="user" alias="userLove"/>
<!-- 使用时
User user2 = (User) context.getBean("userLove");
-->
5.2、Bean的配置
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
<!--id:bean的唯一标识符,也就是相当于我们学的对象名
class:bean对象所对应的会限定名:包名+类型
name:也是别名,而且name可以同时取多个别名 -->
<bean id="user" class="pojo.User" name="u1 u2,u3;u4">
<property name="name" value="chen"/>
</bean>
<!-- 使用时
User user2 = (User) context.getBean("u1");
-->
5.3、import
import一般用于团队开发使用,它可以将多个配置文件,导入合并为一个
假设,现在项目中有多个人开发,这三个人复制不同的类开发,不同的类需要注册在不同的bean中,我们可以利
用import将所有人的beans.xml合并为一个总的!
-
张三(beans.xm1)
-
李四(beans2.xm1)
-
王五(beans3.xm1)
-
applicationContext.xml
复制代码- 1
- 2
- 3
xml<import resource="beans.xm1"/> <import resource="beans2.xml"/> <import resource="beans3.xm1"/>
使用的时候,直接使用总的配置就可以了
弹幕评论:
按照在总的xml中的导入顺序来进行创建,后导入的会重写先导入的,最终实例化的对象会是后导入xml中的那个
6、依赖注入(DI)
6.1、构造器注入
第4点有提到
6.2、set方式注入【重点】
依赖注入:set注入!
- 依赖:bean对象的创建依赖于容器
- 注入:bean对象中的所有属性,由容器来注入
【环境搭建】
-
复杂类型
Address类
-
真实测试对象
Student类
-
beans.xml
-
测试
MyTest3
Student类
复制代码
- 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 pojo;
import java.util.*;
public class Student {
//别忘了写get和set方法(用lombok注解也行)
private String name;
private Address address;
<span class="hljs-keyword">private</span> String[] books;
<span class="hljs-keyword">private</span> List<String> hobbies;
<span class="hljs-keyword">private</span> Map<String, String> card;
<span class="hljs-keyword">private</span> Set<String> game;
<span class="hljs-keyword">private</span> Properties infor;
<span class="hljs-keyword">private</span> String wife;
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"Student{"</span> +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">"name='"</span> + name + <span class="hljs-string">'\''</span> +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", address="</span> + address.toString() +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", books="</span> + Arrays.toString(books) +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", hobbies="</span> + hobbies +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", card="</span> + card +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", game="</span> + game +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", infor="</span> + infor +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">", wife='"</span> + wife + <span class="hljs-string">'\''</span> +<span class="hljs-string">"\n"</span>+
<span class="hljs-string">'}'</span>;
}
}
Address类
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
package pojo;
public class Address {
<span class="hljs-keyword">private</span> String address;
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getAddress</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> address;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAddress</span><span class="hljs-params">(String address)</span> </span>{
<span class="hljs-keyword">this</span>.address = address;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"Address{"</span> +
<span class="hljs-string">"address='"</span> + address + <span class="hljs-string">'\''</span> +
<span class="hljs-string">'}'</span>;
}
}
beans.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
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
<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">
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"address"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.Address"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"address"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"address你好"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"student"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.Student"</span>></span>
<span class="hljs-comment"><!--第一种,普通值注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"name你好"</span> /></span>
<span class="hljs-comment"><!--第二种,ref注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"address"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"address"</span> /></span>
<span class="hljs-comment"><!--数组注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"books"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">array</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>三国<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>西游<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>水浒<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"></<span class="hljs-name">array</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-comment"><!--list列表注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"hobbies"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">list</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>唱<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>跳<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>rap<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>篮球<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"></<span class="hljs-name">list</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-comment"><!--map键值对注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"card"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">map</span>></span>
<span class="hljs-tag"><<span class="hljs-name">entry</span> <span class="hljs-attr">key</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">entry</span> <span class="hljs-attr">key</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">map</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-comment"><!--set(可去重)注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"game"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">set</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>wangzhe<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>lol<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"><<span class="hljs-name">value</span>></span>galname<span class="hljs-tag"></<span class="hljs-name">value</span>></span>
<span class="hljs-tag"></<span class="hljs-name">set</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-comment"><!--空指针null注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"wife"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">null</span>></span><span class="hljs-tag"></<span class="hljs-name">null</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-comment"><!--properties常量注入 --></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"infor"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">props</span>></span>
<span class="hljs-tag"><<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">"id"</span>></span>20200802<span class="hljs-tag"></<span class="hljs-name">prop</span>></span>
<span class="hljs-tag"><<span class="hljs-name">prop</span> <span class="hljs-attr">key</span>=<span class="hljs-string">"name"</span>></span>cbh<span class="hljs-tag"></<span class="hljs-name">prop</span>></span>
<span class="hljs-tag"></<span class="hljs-name">props</span>></span>
<span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
MyTest3
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import pojo.Student;
public class MyTest3 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Student stu = (Student) context.getBean("student");
System.out.println(stu.toString());
}
}
6.3、拓展注入
官方文档位置
pojo增加User类
复制代码
- 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
package pojo;
public class User {
private String name;
private int id;
public User() {
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">User</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> id)</span> </span>{
<span class="hljs-keyword">super</span>();
<span class="hljs-keyword">this</span>.name = name;
<span class="hljs-keyword">this</span>.id = id;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> name;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
<span class="hljs-keyword">this</span>.name = name;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getId</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> id;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setId</span><span class="hljs-params">(<span class="hljs-keyword">int</span> id)</span> </span>{
<span class="hljs-keyword">this</span>.id = id;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"User [name="</span> + name + <span class="hljs-string">", id="</span> + id + <span class="hljs-string">"]"</span>;
}
}
注意: beans 里面加上这下面两行
使用p和c命名空间需要导入xml约束
xmlns:p=“http://www.springframework.org/schema/p”
xmlns:c=“http://www.springframework.org/schema/c”
复制代码
- 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: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">
<span class="hljs-comment"><!--p命名空间注入/set注入,可以直接注入属性的值-》property--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.User"</span> <span class="hljs-attr">p:name</span>=<span class="hljs-string">"cxk"</span> <span class="hljs-attr">p:id</span>=<span class="hljs-string">"20"</span> ></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--c命名空间,通过构造器注入,需要写入有参和无参构造方法-》construct-args--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.User"</span> <span class="hljs-attr">c:name</span>=<span class="hljs-string">"cbh"</span> <span class="hljs-attr">c:id</span>=<span class="hljs-string">"22"</span>></span><span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
测试
复制代码
- 1
- 2
- 3
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
User user = context.getBean("user",User.class);//确定class对象,就不用再强转了
System.out.println(user.toString());
6.4、Bean作用域
-
单例模式(默认)
复制代码- 1
xml<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="singleton"></bean>
弹幕评论:单例模式是把对象放在pool中,需要再取出来,使用的都是同一个对象实例
-
原型模式: 每次从容器中get的时候,都产生一个新对象!
复制代码- 1
xml<bean id="user2" class="pojo.User" c:name="cxk" c:age="19" scope="prototype"></bean>
- 其余的request、session、application这些只能在web开放中使用!
7、Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
-
在xml中显示配置
-
在java中显示配置
-
隐式的自动装配bean 【重要】
-
环境搭建:一个人有两个宠物
-
byType自动装配:byType会自动查找,和自己对象set方法参数的类型相同的bean
保证所有的class唯一(类为全局唯一)
-
byName自动装配:byName会自动查找,和自己对象set对应的值对应的id
保证所有id唯一,并且和set注入的值一致
复制代码- 1
- 2
- 3
- 4
xml<!-- 找不到id和多个相同class --> <bean id="cat1" class="pojo.Cat"/> <bean id="cat2" class="pojo.Cat"/> 找不到 id=cat,且有两个Cat
7.1测试:自动装配
pojo的Cat类
复制代码
- 1
- 2
- 3
- 4
- 5
public class Cat {
public void shut(){
System.out.println("miao");
}
}
pojo的Dog类
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
public class Dog {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">shut</span><span class="hljs-params">()</span></span>{
System.out.println(<span class="hljs-string">"wow"</span>);
}
}
pojo的People类
复制代码
- 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
package pojo;
public class People {
<span class="hljs-keyword">private</span> Cat cat;
<span class="hljs-keyword">private</span> Dog dog;
<span class="hljs-keyword">private</span> String name;
<span class="hljs-function"><span class="hljs-keyword">public</span> Cat <span class="hljs-title">getCat</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> cat;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setCat</span><span class="hljs-params">(Cat cat)</span> </span>{
<span class="hljs-keyword">this</span>.cat = cat;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> Dog <span class="hljs-title">getDog</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> dog;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setDog</span><span class="hljs-params">(Dog dog)</span> </span>{
<span class="hljs-keyword">this</span>.dog = dog;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> name;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
<span class="hljs-keyword">this</span>.name = name;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"People{"</span> +
<span class="hljs-string">"cat="</span> + cat +
<span class="hljs-string">", dog="</span> + dog +
<span class="hljs-string">", name='"</span> + name + <span class="hljs-string">'\''</span> +
<span class="hljs-string">'}'</span>;
}
}
xml配置 -> byType 自动装配
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
<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">
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"cat"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.Cat"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dog"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.Dog"</span>/></span>
<span class="hljs-comment"><!--byType会在容器自动查找,和自己对象属性相同的bean
例如,Dog dog; 那么就会查找pojo的Dog类,再进行自动装配
--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"people"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"pojo.People"</span> <span class="hljs-attr">autowire</span>=<span class="hljs-string">"byType"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"name"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"cbh"</span>></span><span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
xml配置 -> byName 自动装配
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
<bean id="cat" class="pojo.Cat"/>
<bean id="dog" class="pojo.Dog"/>
<!--byname会在容器自动查找,和自己对象set方法的set后面的值对应的id
例如:setDog(),取set后面的字符作为id,则要id = dog 才可以进行自动装配
-->
<bean id="people" class="pojo.People" autowire="byName">
<property name="name" value="cbh"></property>
</bean>
弹幕评论:byName只能取到小写,大写取不到
7.2、使用注解实现自动装配
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/>
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
<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">
<span class="hljs-tag"><<span class="hljs-name">context:annotation-config</span>/></span>
</beans>
7.2.1、@Autowired
默认是byType方式,如果匹配不上,就会byName
在属性上个使用,也可以在set上使用
我们可以不用编写set方法了,前提是自动装配的属性在Spring容器里,且要符合ByName 自动装配
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
public class People {
private Cat cat;
private Dog dog;
private String name;
}
@Nullable 字段标记了这个注解,说明该字段可以为空
public name(@Nullable String name){
}
复制代码
- 1
- 2
- 3
- 4
//源码
public Autowired {
boolean required() default true;
}
如果定义了Autowire的require属性为false,说明这个对象可以为null,否则不允许为空(false表示找不到装配,不抛出异常)
7.2.2、@Autowired+@Qualifier
@Autowired不能唯一装配时,需要@Autowired+@Qualifier
如果@Autowired自动装配环境比较复杂。自动装配无法通过一个注解完成的时候,可以使用@Qualifier(value = “dog”)去配合使用,指定一个唯一的id对象
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class People {
private Cat cat;
private Dog dog;
private String name;
}
弹幕评论:
如果xml文件中同一个对象被多个bean使用,Autowired无法按类型找到,可以用@Qualifier指定id查找
7.2.3、@Resource
默认是byName方式,如果匹配不上,就会byType
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
public class People {
Resource(name="cat")
private Cat cat;
Resource(name="dog")
private Dog dog;
private String name;
}
弹幕评论:
Autowired是byType,@Autowired+@Qualifier = byType || byName
Autowired是先byteType,如果唯一則注入,否则byName查找。resource是先byname,不符合再继续byType
区别:
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
- 执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byname的方式实现
8、使用注解开发
在spring4之后,使用注解开发,必须要保证aop包的导入
使用注解需要导入contex的约束
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
<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">
<span class="hljs-tag"><<span class="hljs-name">context:annotation-config</span>/></span>
</beans>
8.1、bean
弹幕评论:
有了< context:component-scan>,另一个< context:annotation-config/>标签可以移除掉,因为已经被包含进去了。
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
<!--指定要扫描的包,这个包下面的注解才会生效
别只扫一个com.kuang.pojo包-->
<context:component-scan base-package="com.kuang"/>
<context:annotation-config/>
1234
//@Component 组件
//等价于<bean id="user" classs"pojo.User"/>
@Component
public class User {
public String name ="秦疆";
}
8.2、属性如何注入@value
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
public class User {
//相当于<property name="name" value="kuangshen"/>
public String name;
<span class="hljs-comment">//也可以放在set方法上面</span>
<span class="hljs-comment">//@value("kuangshen")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
<span class="hljs-keyword">this</span>.name = name;
}
}
8.3、衍生的注解
@Component有几个衍生注解,会按照web开发中,mvc架构中分层。
- dao (@Repository)
- service(@Service)
- controller(@Controller)
这四个注解的功能是一样的,都是代表将某个类注册到容器中
8.4、自动装配置
@Autowired:默认是byType方式,如果匹配不上,就会byName
@Nullable:字段标记了这个注解,说明该字段可以为空
@Resource:默认是byName方式,如果匹配不上,就会byType
8.5、作用域@scope
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
//原型模式prototype,单例模式singleton
//scope("prototype")相当于<bean scope="prototype"></bean>
public class User {
<span class="hljs-comment">//相当于<property name="name" value="kuangshen"/> </span>
<span class="hljs-meta">@value("kuangshen")</span>
<span class="hljs-keyword">public</span> String name;
<span class="hljs-comment">//也可以放在set方法上面</span>
<span class="hljs-meta">@value("kuangshen")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
<span class="hljs-keyword">this</span>.name = name;
}
}
8.6、小结
xml与注解:
- xml更加万能,维护简单,适用于任何场合
- 注解,不是自己的类使用不了,维护复杂
最佳实践:
- xml用来管理bean
- 注解只用来完成属性的注入
- 要开启注解支持
9、使用Java的方式配置Spring
不使用Spring的xml配置,完全交给java来做!
Spring的一个子项目,在spring4之后,,,它成为了核心功能
实体类:pojo的User.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
//这里这个注解的意思,就是说明这个类被Spring接管了,注册到了容器中
public class User {
private String name;
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> name;
}
<span class="hljs-comment">//属性注入值</span>
<span class="hljs-meta">@value("QINJIANG')</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
<span class="hljs-keyword">this</span>.name = name;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">toString</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> <span class="hljs-string">"user{"</span> +
<span class="hljs-string">"name='"</span> + name + <span class="hljs-string">'\''</span>+
<span class="hljs-string">'}'</span>;
}
}
弹幕评论:要么使用@Bean,要么使用@Component和ComponentScan,两种效果一样
配置文件:config中的kuang.java
@Import(KuangConfig2.class),用@import来包含KuangConfig2.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
//这个也会Spring容器托管,注册到容器中,因为他本米就是一个@Component
// @Configuration表这是一个配置类,就像我们之前看的beans.xml,类似于<beans>标签
//开启扫描
//@Import(KuangConfig2.class)
public class KuangConfig {
//注册一个bean , 就相当于我们之前写的一个bean 标签
//这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser
//这个方法的返同值,就相当于bean 标签中的class 属性 ->User
<span class="hljs-comment">//@Bean </span>
<span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> User(); <span class="hljs-comment">//就是返回要注入到bean的对象! </span>
}
}
弹幕评论:ComponentScan、@Component("pojo”) 这两个注解配合使用
测试类
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class MyTest {
public static void main(String[ ] args) {
//如果完全使用了配置类方式去做,我们就只能通过 Annotationconfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); //class对象
User getUser =(User)context.getBean( "getUser"); //方法名getUser
System.out.Println(getUser.getName());
}
}
会创建两个相同对象问题的说明:
弹幕总结 - -> @Bean是相当于< bean>标签创建的对象,而我们之前学的@Component是通过spring自动创建的这个被注解声明的对象,所以这里相当于有两个User对象被创建了。一个是bean标签创建的(@Bean),一个是通过扫描然后使用@Component,spring自动创建的User对象,所以这里去掉@Bean这些东西,然后开启扫描。之后在User头上用@Component即可达到spring自动创建User对象了
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
//这个也会Spring容器托管,注册到容器中,因为他本米就是一个@Component
// @Configuration表这是一个配置类,就像我们之前看的beans.xml,类似于<beans>标签
//开启扫描
//@Import(KuangConfig2.class)
public class KuangConfig {
//注册一个bean , 就相当于我们之前写的一个bean 标签
//这个方法的名字,就相当于bean 标签中的 id 属性 ->getUser
//这个方法的返同值,就相当于bean 标签中的class 属性 ->User
<span class="hljs-comment">//@Bean </span>
<span class="hljs-function"><span class="hljs-keyword">public</span> User <span class="hljs-title">getUser</span><span class="hljs-params">()</span></span>{
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> User(); <span class="hljs-comment">//就是返回要注入到bean的对象! </span>
}
}
弹幕评论:ComponentScan、@Component("pojo”) 这两个注解配合使用
测试类
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class MyTest {
public static void main(String[ ] args) {
//如果完全使用了配置类方式去做,我们就只能通过 Annotationconfig 上下文来获取容器,通过配置类的class对象加载!
ApplicationContext context = new AnnotationConfigApplicationContext(KuangConfig.Class); //class对象
User getUser =(User)context.getBean( "getUser"); //方法名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、接口
复制代码
- 1
- 2
- 3
- 4
package pojo;
public interface Host {
public void rent();
}
2、真实角色
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
package pojo;
public class HostMaster implements Host{
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rent</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"房东要出租房子"</span>);
}
}
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 pojo;
public class Proxy {
<span class="hljs-keyword">public</span> Host host;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Proxy</span><span class="hljs-params">()</span> </span>{
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Proxy</span><span class="hljs-params">(Host host)</span> </span>{
<span class="hljs-keyword">super</span>();
<span class="hljs-keyword">this</span>.host = host;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">rent</span><span class="hljs-params">()</span> </span>{
seeHouse();
host.rent();
fee();
sign();
}
<span class="hljs-comment">//看房</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">seeHouse</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"看房子"</span>);
}
<span class="hljs-comment">//收费</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fee</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"收中介费"</span>);
}
<span class="hljs-comment">//合同</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">sign</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"签合同"</span>);
}
}
4、客户端访问代理角色
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
package holle4_proxy;
import pojo.Host;
import pojo.HostMaster;
import pojo.Proxy;
public class My {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-comment">//房东要出租房子</span>
Host host = <span class="hljs-keyword">new</span> HostMaster();
<span class="hljs-comment">//中介帮房东出租房子,但也收取一定费用(增加一些房东不做的操作)</span>
Proxy proxy = <span class="hljs-keyword">new</span> Proxy(host);
<span class="hljs-comment">//看不到房东,但通过代理,还是租到了房子</span>
proxy.rent();
}
}
代码翻倍:几十个真实角色就得写几十个代理
AOP横向开发
10.2、动态代理
动态代理和静态角色一样,动态代理底层是反射机制
动态代理类是动态生成的,不是我们直接写好的!
动态代理(两大类):基于接口,基于类
- 基于接口:JDK的动态代理【使用ing】
- 基于类:cglib
- java字节码实现:javasisit
了解两个类
1、Proxy:代理
2、InvocationHandler:调用处理程序
实例:
接口 Host.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
//接口
package pojo2;
public interface Host {
public void rent();
}
接口Host实现类 HostMaster.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
//接口实现类
package pojo2;
public class HostMaster implements Host{
public void rent() {
System.out.println("房东要租房子");
}
}
代理角色的处理程序类 ProxyInvocationHandler.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 pojo2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
///用这个类,自动生成代理
public class ProxyInvocationHandler implements InvocationHandler {
<span class="hljs-comment">// Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),</span>
<span class="hljs-comment">// new Class<?>[] { Foo.Class },</span>
<span class="hljs-comment">// handler);</span>
<span class="hljs-comment">// 被代理的接口</span>
<span class="hljs-keyword">public</span> HostMaster hostMaster ;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setHostMaster</span><span class="hljs-params">(HostMaster hostMaster)</span> </span>{
<span class="hljs-keyword">this</span>.hostMaster = hostMaster;
}
<span class="hljs-comment">// 得到生成的代理类 </span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getProxy</span><span class="hljs-params">()</span> </span>{
<span class="hljs-comment">// newProxyInstance() -> 生成代理对象,就不用再写具体的代理类了</span>
<span class="hljs-comment">// this.getClass().getClassLoader() -> 找到加载类的位置</span>
<span class="hljs-comment">// hostMaster.getClass().getInterfaces() -> 代理的具体接口</span>
<span class="hljs-comment">// this -> 代表了接口InvocationHandler的实现类ProxyInvocationHandler</span>
<span class="hljs-keyword">return</span> Proxy.newProxyInstance(<span class="hljs-keyword">this</span>.getClass().getClassLoader(), hostMaster.getClass().getInterfaces(), <span class="hljs-keyword">this</span>);
<span class="hljs-comment">// 处理代理实例并返回结果</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy, Method method, Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>{
seeHouse();
<span class="hljs-comment">// 动态代理的本质,就是使用反射机制实现的</span>
<span class="hljs-comment">// invoke()执行它真正要执行的方法</span>
Object result = method.invoke(hostMaster, args);
fee();
<span class="hljs-keyword">return</span> result;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">seeHouse</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"看房子"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">fee</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"收中介费"</span>);
}
}
用户类 My2.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
package holle4_proxy;
import pojo2.Host;
import pojo2.Host2;
import pojo2.HostMaster;
import pojo2.ProxyInvocationHandler;
public class My2 {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-comment">//真实角色</span>
HostMaster hostMaster = <span class="hljs-keyword">new</span> HostMaster();
<span class="hljs-comment">//代理角色,现在没有;用代理角色的处理程序来实现Host接口的调用</span>
ProxyInvocationHandler pih = <span class="hljs-keyword">new</span> ProxyInvocationHandler();
<span class="hljs-comment">//pih -> HostMaster接口类 -> Host接口</span>
pih.setHostMaster(hostMaster);
<span class="hljs-comment">//获取newProxyInstance动态生成代理类</span>
Host proxy = (Host) pih.getProxy();
proxy.rent();
}
}
弹幕评论:
什么时候调用invoke方法的?
代理实例调用方法时invoke方法就会被调用,可以debug试试
改为万能代理类
复制代码
- 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
///用这个类,自动生代理
public class ProxyInvocationHandler implements InvocationHandler {
<span class="hljs-comment">// Foo f =(Foo) Proxy.NewProxyInstance(Foo. Class.GetClassLoader(),</span>
<span class="hljs-comment">// new Class<?>[] { Foo.Class },</span>
<span class="hljs-comment">// handler);</span>
<span class="hljs-comment">// 被代理的接口</span>
<span class="hljs-keyword">public</span> Object target;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setTarget</span><span class="hljs-params">(Object target)</span> </span>{
<span class="hljs-keyword">this</span>.target = target;
}
<span class="hljs-comment">// 得到生成的代理类 -> 固定的代码</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">getProxy</span><span class="hljs-params">()</span> </span>{
<span class="hljs-comment">// newProxyInstance() -> 生成代理对象,就不用再写具体的代理类了</span>
<span class="hljs-comment">// this.getClass().getClassLoader() -> 找到加载类的位置</span>
<span class="hljs-comment">// hostMaster.getClass().getInterfaces() -> 代理的具体接口</span>
<span class="hljs-comment">// this -> 代表了接口InvocationHandler的实现类ProxyInvocationHandler</span>
<span class="hljs-keyword">return</span> Proxy.newProxyInstance(<span class="hljs-keyword">this</span>.getClass().getClassLoader(),
target.getClass().getInterfaces(), <span class="hljs-keyword">this</span>);
}
<span class="hljs-comment">// 处理代理实例并返回结果</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy, Method method, Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>{
<span class="hljs-comment">//前置通知</span>
pre();
<span class="hljs-comment">//打印日志,通过反射的方式</span>
log(method.getName());
<span class="hljs-comment">// 动态代理的本质,就是使用反射机制实现的</span>
<span class="hljs-comment">// invoke()执行它真正要执行的方法</span>
Object result = method.invoke(target, args);
<span class="hljs-comment">//后置通知</span>
post();
<span class="hljs-keyword">return</span> result;
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">pre</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"[前置通知]"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">post</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"[后置通知]"</span>);
}
<span class="hljs-comment">//日志打印</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">log</span><span class="hljs-params">(String msg)</span> </span>{
System.out.println(<span class="hljs-string">"[Debug]执行了"</span> + msg + <span class="hljs-string">"方法"</span>);
}
}
测试类:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
public class Client {
public static void main(String[] args) {
//真实角色
UserServiceImpl userService = new UserServiceImpl();
<span class="hljs-comment">//代理角色,不存在</span>
ProxyInvocationHandler proxyInvocationHandler = <span class="hljs-keyword">new</span> ProxyInvocationHandler();
<span class="hljs-comment">//设置要代理的对象</span>
proxyInvocationHandler.setTarget(userService);
<span class="hljs-comment">//动态生产代理类</span>
UserService proxy = (UserService) proxyInvocationHandler.getProxy();
<span class="hljs-comment">//执行业务操作</span>
proxy.add();
}
}
11、AOP
11.1、什么是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织入,需要导入一个依赖包!
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
<!-- 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接口
springAPI接口实现
需要先导入aop约束
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
<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>
applicationContext.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
<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">
<span class="hljs-comment"><!--注册bean--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userservice"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"service.UserServiceImpl"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"log"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"log.Log"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"afterLog"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"log.AfterLog"</span>/></span>
<span class="hljs-comment"><!--方式一,使用原生Spring API接口--></span>
<span class="hljs-comment"><!--配置aop,还需要导入aop约束--></span>
<span class="hljs-tag"><<span class="hljs-name">aop:config</span>></span>
<span class="hljs-comment"><!--切入点:expression:表达式,execution(要执行的位置)--></span>
<span class="hljs-tag"><<span class="hljs-name">aop:pointcut</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"pointcut"</span> <span class="hljs-attr">expression</span>=<span class="hljs-string">"execution(* service.UserServiceImpl.*(..))"</span>/></span>
<span class="hljs-comment"><!--UserServiceImpl.*(..) -》 UserServiceImpl类下的所以方法(参数)--></span>
<span class="hljs-comment"><!--执行环绕增加--></span>
<span class="hljs-tag"><<span class="hljs-name">aop:advisor</span> <span class="hljs-attr">advice-ref</span>=<span class="hljs-string">"log"</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">"pointcut"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">aop:advisor</span> <span class="hljs-attr">advice-ref</span>=<span class="hljs-string">"afterLog"</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">"pointcut"</span>/></span>
<span class="hljs-comment"><!-- 环绕,在id="pointcut"的前后切入 --></span>
<span class="hljs-tag"></<span class="hljs-name">aop:config</span>></span>
</beans>
execution(返回类型,类名,方法名(参数)) -> execution(* com.service.*,*(…))
UserService.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
package service;
public interface UserService {
public void add() ;
public void delete() ;
public void query() ;
public void update();
}
UserService 的实现类 UserServiceImp.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
package service;
public class UserServiceImpl implements UserService {
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">add</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"add增"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">delete</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"delete删"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">update</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"update改"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">query</span><span class="hljs-params">()</span> </span>{
System.out.println(<span class="hljs-string">"query查"</span>);
}
}
前置Log.java
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
package 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
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
package log;
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class AfterLog implements AfterReturningAdvice {
//returnVaule: 返回值
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("执行了"+method.getName()+"方法,返回值是"+returnValue);
}
}
测试类MyTest5
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.UserService;
public class MyTest5 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//注意:动态代理代理的是接口
UserService userService = (UserService) context.getBean("userservice");
userService.add();
}
}
11.3.2、方法二:自定义类实现AOP
复制代码
- 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
<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="service.UserServiceImpl"/>
<bean id="log" class="log.Log"/>
<bean id="afterLog" class="log.AfterLog"/>
<!-- 方式二,自定义 -->
<bean id="diy" class="diy.DiyPointcut"/>
<aop:config>
<!--自定义切面-->
<aop:aspect ref="diy">
<!--切入点-->
<aop:pointcut id="point" expression="execution(* service.UserServiceImpl.*(..))"/>
<aop:before method="before" pointcut-ref="point"/>
<aop:after method="after" pointcut-ref="point"/>
</aop:aspect>
</aop:config>
</beans>
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
package diy;
public class DiyPointcut {
public void before(){
System.out.println("插入到前面");
}
public void after(){
System.out.println("插入到后面");
}
}
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
//测试
public class MyTest5 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//注意:动态代理代理的是接口
UserService userService = (UserService) context.getBean("userservice");
userService.add();
}
}
11.3.3、方法三:使用注解实现
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
<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">
<span class="hljs-comment"><!-- 注册 --></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userservice"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"service.UserServiceImpl"</span>/></span>
<span class="hljs-comment"><!--方式三,使用注解实现--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"diyAnnotation"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"diy.DiyAnnotation"</span>></span><span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!-- 开启自动代理
实现方式:默认JDK (proxy-targer-class="fasle")
cglib (proxy-targer-class="true")--></span>
<span class="hljs-tag"><<span class="hljs-name">aop:aspectj-autoproxy</span>/></span>
</beans>
DiyAnnotation.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
package diy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
//标注这个类是一个切面
public class DiyAnnotation {
<span class="hljs-meta">@Before("execution(* service.UserServiceImpl.*(..))")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">before</span><span class="hljs-params">()</span></span>{
System.out.println(<span class="hljs-string">"=====方法执行前====="</span>);
}
<span class="hljs-meta">@After("execution(* service.UserServiceImpl.*(..))")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">after</span><span class="hljs-params">()</span></span>{
System.out.println(<span class="hljs-string">"=====方法执行后====="</span>);
}
<span class="hljs-comment">//在环绕增强中,我们可以给地暖管一个参数,代表我们要获取切入的点</span>
<span class="hljs-meta">@Around("execution(* service.UserServiceImpl.*(..))")</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">around</span><span class="hljs-params">(ProceedingJoinPoint joinPoint)</span> <span class="hljs-keyword">throws</span> Throwable </span>{
System.out.println(<span class="hljs-string">"环绕前"</span>);
Object proceed = joinPoint.proceed();
System.out.println(<span class="hljs-string">"环绕后"</span>);
}
}
测试
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
public class MyTest5 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//注意:动态代理代理的是接口
UserService userService = (UserService) context.getBean("userservice");
userService.add();
}
}
输出结果:
12、整合mybatis
【提醒】:
本节知识密度大,时间长,需要多看几遍视频,加深理解
步骤:
- 导入相关jar
- junit
- mybatis
- mysql数据库
- spring相关的
- aop织入
- mybatis-spring【new】
- 编写配置文件
- 测试
mybatis-spring官网:https://mybatis.org/spring/zh/
12.0、回忆Mybatis
mybatis的配置流程:
- 编写实体类
- 编写核心配置文件
- 编写接口
- 编写Mapper.xmi
- 测试
实例:
- 导入相关jar,pom.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
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-study</artifactId>
<groupId>com.melodyhub</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-10-mybatis<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependencies</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>junit<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>junit<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>4.12<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"><<span class="hljs-name">scope</span>></span>test<span class="hljs-tag"></<span class="hljs-name">scope</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>mysql<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mysql-connector-java<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-comment"><!--<version>5.1.47</version>--></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>8.0.19<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>3.5.3<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-webmvc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.0.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-comment"><!--Spring操作数据库的话,需要一个spring-jdbc--></span>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-jdbc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.5.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.aspectj<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>aspectjweaver<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.9.4<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis-spring<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>2.0.3<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.projectlombok<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>lombok<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.18.10<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependencies</span>></span>
<span class="hljs-comment"><!--在build中配置resources,来防止资源导出失败的问题--></span>
<span class="hljs-comment"><!-- Maven解决静态资源过滤问题 --></span>
<span class="hljs-tag"><<span class="hljs-name">build</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resources</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">directory</span>></span>src/main/java<span class="hljs-tag"></<span class="hljs-name">directory</span>></span>
<span class="hljs-tag"><<span class="hljs-name">includes</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.properties<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.xml<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"></<span class="hljs-name">includes</span>></span>
<span class="hljs-comment"><!--<filtering>false</filtering>--></span>
<span class="hljs-tag"><<span class="hljs-name">filtering</span>></span>true<span class="hljs-tag"></<span class="hljs-name">filtering</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">directory</span>></span>src/main/resources<span class="hljs-tag"></<span class="hljs-name">directory</span>></span>
<span class="hljs-tag"><<span class="hljs-name">includes</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.properties<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.xml<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"></<span class="hljs-name">includes</span>></span>
<span class="hljs-comment"><!--<filtering>true</filtering>--></span>
<span class="hljs-tag"><<span class="hljs-name">filtering</span>></span>false<span class="hljs-tag"></<span class="hljs-name">filtering</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resources</span>></span>
<span class="hljs-tag"></<span class="hljs-name">build</span>></span>
</project>
- 编写实体类,User.java:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
package com.melodyhub.pojo;
import lombok.Data;
public class User {
private int id;
private String name;
private String pwd;
}
- 编写核心配置文件,resources/mybatis-config.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
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration 核心配置文件-->
<configuration>
<!--开启日志-->
<!--<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>-->
<!--可以给实体类起别名 -->
<typeAliases>
<package name="com.melodyhub.pojo"/>
</typeAliases>
<!--environments 可配置多个环境-->
<environments default="development">
<!--多个环境,不同id-->
<environment id="development">
<!--事务管理-->
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--<property name="driver" value="com.mysql.jdbc.Driver"/>-->
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册!!!-->
<mappers>
<mapper class="com.melodyhub.mapper.UserMapper"/>
<!--<mapper resource="com/melodyhub/mapper/UserMapper.xml"/>-->
</mappers>
</configuration>
- 编写接口,UserMapper.xml:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
package com.melodyhub.mapper;
import com.melodyhub.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
- 编写接口配置文件,UserMapper.xml:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
<mapper namespace="com.melodyhub.mapper.UserMapper">
<!-- 绑定接口 -->
<select id="selectUser" resultType="user">
select * from mybatis.user;
</select>
</mapper>
- 测试,test/java/MyTest.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
import com.melodyhub.mapper.UserMapper;
import com.melodyhub.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
public void test() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = <span class="hljs-keyword">new</span> SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession(<span class="hljs-keyword">true</span>);
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
<span class="hljs-keyword">for</span> (User user : userList) {
System.out.println(user);
}
}
}
- 结果:
复制代码
- 1
- 2
- 3
- 4
- 5
User(id=1, name=狂神, pwd=123456)
User(id=2, name=张三, pwd=abcdef)
User(id=3, name=李四, pwd=987654)
Process finished with exit code 0
12.1、mybatis-spring-方式一
- 编写数据源配置
sqISessionFactorysqISessionTemplate(相当于sqISession)- 需要给接口加实现类【new】
- 将自己写的实现类,注入到Spring中
- 测试!
数据源:
-
DataSource:使用Spring的数帮源替换Mybatis的配置 -
这使用Spring提供的JDBC:
org.springframework.jdbc.datasource -
其他数据源:
c3p0、dbcp、druid
【核心对象】:
sqISessionFactory
在基础的 MyBatis 用法中,是通过
SqlSessionFactoryBuilder来创建SqlSessionFactory的。 而在 MyBatis-Spring 中,则使用SqlSessionFactoryBean来创建。
sqISessionTemplate
SqlSessionTemplate是 MyBatis-Spring 的核心。作为SqlSession的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的SqlSession。SqlSessionTemplate是线程安全的,可以被多个 DAO 或映射器所共享使用。当调用 SQL 方法时(包括由
getMapper()方法返回的映射器中的方法),SqlSessionTemplate将会保证使用的SqlSession与当前 Spring 的事务相关。此外,它管理 session 的生命周期,包含必要的关闭、提交或回滚操作。另外,它也负责将 MyBatis 的异常翻译成 Spring 中的DataAccessExceptions。由于模板可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用
SqlSessionTemplate来替换 MyBatis 默认的DefaultSqlSession实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。可以使用
SqlSessionFactory作为构造方法的参数来创建SqlSessionTemplate对象。

先导入jar包,
复制代码
- 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
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-study</artifactId>
<groupId>com.melodyhub</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-10-mybatis<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependencies</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>junit<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>junit<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>4.12<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"><<span class="hljs-name">scope</span>></span>test<span class="hljs-tag"></<span class="hljs-name">scope</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>mysql<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mysql-connector-java<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-comment"><!--<version>5.1.47</version>--></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>8.0.19<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>3.5.3<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-webmvc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.0.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-comment"><!--Spring操作数据库的话,需要一个spring-jdbc--></span>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-jdbc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.5.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.aspectj<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>aspectjweaver<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.9.4<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis-spring<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>2.0.3<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.projectlombok<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>lombok<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.18.10<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependencies</span>></span>
<span class="hljs-comment"><!--在build中配置resources,来防止资源导出失败的问题--></span>
<span class="hljs-comment"><!-- Maven解决静态资源过滤问题 --></span>
<span class="hljs-tag"><<span class="hljs-name">build</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resources</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">directory</span>></span>src/main/java<span class="hljs-tag"></<span class="hljs-name">directory</span>></span>
<span class="hljs-tag"><<span class="hljs-name">includes</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.properties<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.xml<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"></<span class="hljs-name">includes</span>></span>
<span class="hljs-comment"><!--<filtering>false</filtering>--></span>
<span class="hljs-tag"><<span class="hljs-name">filtering</span>></span>true<span class="hljs-tag"></<span class="hljs-name">filtering</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"><<span class="hljs-name">directory</span>></span>src/main/resources<span class="hljs-tag"></<span class="hljs-name">directory</span>></span>
<span class="hljs-tag"><<span class="hljs-name">includes</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.properties<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"><<span class="hljs-name">include</span>></span>**/*.xml<span class="hljs-tag"></<span class="hljs-name">include</span>></span>
<span class="hljs-tag"></<span class="hljs-name">includes</span>></span>
<span class="hljs-comment"><!--<filtering>true</filtering>--></span>
<span class="hljs-tag"><<span class="hljs-name">filtering</span>></span>false<span class="hljs-tag"></<span class="hljs-name">filtering</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resource</span>></span>
<span class="hljs-tag"></<span class="hljs-name">resources</span>></span>
<span class="hljs-tag"></<span class="hljs-name">build</span>></span>
</project>
关于解决“Maven解决静态资源过滤问题”详见:Maven中静态资源和字节码文件的过滤

编写顺序:
User -> UserMapper -> UserMapper.xml -> spring-dao.xml -> UserServiceImpl -> applicationContext.xml -> MyTest6
代码步骤:
pojo实体类 User:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
package com.melodyhub.pojo;
import lombok.Data;
public class User {
private int id;
private String name;
private String pwd;
}
mapper目录下的 UserMapper、UserMapperImpl、UserMapper.xml
接口UserMapper:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
package com.melodyhub.mapper;
import com.melodyhub.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> selectUser();
}
UserMapperImpl:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
package com.melodyhub.mapper;
import com.melodyhub.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;
import java.util.List;
public class UserMapperImpl implements UserMapper {
//我们的所有操作,在原来都使用sqlSession来执行,现在都使用SqlSessionTemplate;
private SqlSessionTemplate sqlSession;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setSqlSession</span><span class="hljs-params">(SqlSessionTemplate sqlSession)</span> </span>{
<span class="hljs-keyword">this</span>.sqlSession = sqlSession;
}
<span class="hljs-meta">@Override</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> List<User> <span class="hljs-title">selectUser</span><span class="hljs-params">()</span> </span>{
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
<span class="hljs-keyword">return</span> userMapper.selectUser();
}
}
UserMapper.xml:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
<mapper namespace="com.melodyhub.mapper.UserMapper">
<!-- 绑定接口 -->
<select id="selectUser" resultType="user">
select * from mybatis.user;
</select>
</mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.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
<!--configuration 核心配置文件-->
<configuration>
<span class="hljs-comment"><!--开启日志--></span>
<span class="hljs-comment"><!--<settings>
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>--></span>
<span class="hljs-comment"><!--可以给实体类起别名 --></span>
<span class="hljs-tag"><<span class="hljs-name">typeAliases</span>></span>
<span class="hljs-tag"><<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"com.melodyhub.pojo"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">typeAliases</span>></span>
<span class="hljs-comment"><!--environments 可配置多个环境--></span>
<span class="hljs-comment"><!--配置了Spring-Dao.xml后,这块可以直接注释掉了:dataSource
<environments default="development">
&lt;!&ndash;多个环境,不同id&ndash;&gt;
<environment id="development">
&lt;!&ndash;事务管理&ndash;&gt;
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
&lt;!&ndash;<property name="driver" value="com.mysql.jdbc.Driver"/>&ndash;&gt;
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;autoReconnect=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>--></span>
<span class="hljs-comment"><!--每一个Mapper.xml都需要在MyBatis核心配置文件中注册!!!--></span>
<span class="hljs-comment"><!-- 配置了Spring-Dao.xml后,这块可以直接注释掉了:绑定Mybatis配置文件
<mappers>
<mapper class="com.melodyhub.mapper.UserMapper"/>
&lt;!&ndash;<mapper resource="com/melodyhub/mapper/UserMapper.xml"/>&ndash;&gt;
</mappers>--></span>
</configuration>
spring-dao.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
<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">
<span class="hljs-comment"><!--DataSource:使用Spring的数帮源替换Mybatis的配置 其他数据源:c3p0、dbcp、druid
这使用Spring提供的JDBC: org.springframework.jdbc.datasource --></span>
<span class="hljs-comment"><!--dataSource --></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driverClassName"</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">"com.mysql.cj.jdbc.Driver"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"jdbc:mysql://localhost:3306/mybatis?useSSL=true<span class="hljs-symbol">&amp;</span>useUnicode=true<span class="hljs-symbol">&amp;</span>characterEncoding=utf8<span class="hljs-symbol">&amp;</span>serverTimezone=GMT%2B8<span class="hljs-symbol">&amp;</span>autoReconnect=true"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--sqlSessionFactory--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.mybatis.spring.SqlSessionFactoryBean"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dataSource"</span> /></span>
<span class="hljs-comment"><!--绑定 Mybatis 配置文件--></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"configLocation"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:mybatis-config.xml"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"mapperLocations"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:com/melodyhub/mapper/*.xml"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!-- sqlSessionTemplate 就是之前使用的:sqlsession --></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sqlSession"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.mybatis.spring.SqlSessionTemplate"</span>></span>
<span class="hljs-comment"><!-- 只能使用构造器注入sqlSessionFactory 原因:它没有set方法--></span>
<span class="hljs-tag"><<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">index</span>=<span class="hljs-string">"0"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSessionFactory"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
applicationContext.xml:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
<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">
<span class="hljs-comment"><!--导入其他配置文件--></span>
<span class="hljs-tag"><<span class="hljs-name">import</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"spring-dao.xml"</span>/></span>
<span class="hljs-comment"><!--<import resource="spring-mvc.xml"/>--></span>
<span class="hljs-comment"><!--mybatis-spring 方式1--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userMapper"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"com.melodyhub.mapper.UserMapperImpl"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"sqlSession"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSession"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
测试类:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
import com.melodyhub.mapper.UserMapper;
import com.melodyhub.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class MyTest {
public void test1() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
for (User user : userMapper.selectUser()) {
System.out.println(user);
}
}
}
12.2、mybatis-spring-方式二
SqlSessionDaoSupport
SqlSessionDaoSupport是一个抽象的支持类,用来为你提供SqlSession。调用getSqlSession()方法你会得到一个SqlSessionTemplate,之后可以用于执行 SQL 方法,就像下面这样:复制代码
- 1
- 2
- 3
- 4
- 5
javapublic class UserDaoImpl extends SqlSessionDaoSupport implements UserDao { public User getUser(String userId) { return getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId); } }在这个类里面,通常更倾向于使用
MapperFactoryBean,因为它不需要额外的代码。但是,如果你需要在 DAO 中做其它非 MyBatis 的工作或需要一个非抽象的实现类,那么这个类就很有用了。
SqlSessionDaoSupport需要通过属性设置一个sqlSessionFactory或SqlSessionTemplate。如果两个属性都被设置了,那么SqlSessionFactory将被忽略。假设类
UserMapperImpl是SqlSessionDaoSupport的子类,可以编写如下的 Spring 配置来执行设置:复制代码
- 1
- 2
- 3
xml<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
UserServiceImpl2.java:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
package com.melodyhub.mapper;
import com.melodyhub.pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
/*
SqlSession sqlSession = getSqlSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
return userMapper.selectUser();
*/
return getSqlSession().getMapper(UserMapper.class).selectUser();
}
}
spring-dao.xml:SqlSessionTemplate可以不写了
复制代码
- 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
<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">
<span class="hljs-comment"><!--DataSource:使用Spring的数帮源替换Mybatis的配置 其他数据源:c3p0、dbcp、druid
这使用Spring提供的JDBC: org.springframework.jdbc.datasource --></span>
<span class="hljs-comment"><!--dataSource --></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driverClassName"</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">"com.mysql.cj.jdbc.Driver"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"jdbc:mysql://localhost:3306/mybatis?useSSL=true<span class="hljs-symbol">&amp;</span>useUnicode=true<span class="hljs-symbol">&amp;</span>characterEncoding=utf8<span class="hljs-symbol">&amp;</span>serverTimezone=GMT%2B8<span class="hljs-symbol">&amp;</span>autoReconnect=true"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--sqlSessionFactory--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.mybatis.spring.SqlSessionFactoryBean"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"dataSource"</span> /></span>
<span class="hljs-comment"><!--绑定 Mybatis 配置文件--></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"configLocation"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:mybatis-config.xml"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"mapperLocations"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:com/melodyhub/mapper/*.xml"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!-- 方法二:SqlSessionTemplate 可以不写了--></span>
</beans>
applicationContext.xml:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
<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">
<span class="hljs-comment"><!--导入其他配置文件--></span>
<span class="hljs-tag"><<span class="hljs-name">import</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"spring-dao.xml"</span>/></span>
<span class="hljs-comment"><!--<import resource="spring-mvc.xml"/>--></span>
<span class="hljs-comment"><!--mybatis-spring 方式-2--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userMapper2"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"com.melodyhub.mapper.UserMapperImpl2"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSessionFactory"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
测试:
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
public class MyTest6 {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserMapper userMapper = (UserMapper) context.getBean("userMapper2");
for (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
13. 声明式事务
- 把一组业务当成一个业务来做;要么都成功,要么都失败!
- 事务在项目开发中,十分的重要,涉及到数据的一致性问题
- 确保完整性和一致性
事务的ACID原则:
1、原子性
2、隔离性
3、一致性
4、持久性
ACID参考文章:https://www.cnblogs.com/melodyjerry/p/13621129.html
Spring中的事务管理
- 声明式事务:AOP
- 编程式事务:需要再代码中,进行事务管理
声明式事务
先导入jar包
复制代码
- 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
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
<dependencies>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-webmvc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.7.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.aspectj<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>aspectjweaver<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.9.4<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-comment"><!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.springframework<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>spring-jdbc<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>5.2.7.RELEASE<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>3.5.2<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.mybatis<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mybatis-spring<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>2.0.4<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>mysql<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>mysql-connector-java<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>8.0.12<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">dependency</span>></span>
<span class="hljs-tag"><<span class="hljs-name">groupId</span>></span>org.projectlombok<span class="hljs-tag"></<span class="hljs-name">groupId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">artifactId</span>></span>lombok<span class="hljs-tag"></<span class="hljs-name">artifactId</span>></span>
<span class="hljs-tag"><<span class="hljs-name">version</span>></span>1.18.12<span class="hljs-tag"></<span class="hljs-name">version</span>></span>
<span class="hljs-tag"></<span class="hljs-name">dependency</span>></span>
</dependencies>
<!--在build中配置resources,来防止资源导出失败的问题-->
<!-- Maven解决静态资源过滤问题 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>/*.properties</include>
<include>/.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
代码步骤:
pojo实体类 User
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
package pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
public class User {
private int id;
private String name;
private String pwd;
}
mapper目录下的 UserMapper、UserMapperImpl、UserMapper.xml
接口UserMapper
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
package mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import pojo.User;
public interface UserMapper {
public List<User> getUser();
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">insertUser</span><span class="hljs-params">(User user)</span></span>;
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">delUser</span><span class="hljs-params">(<span class="hljs-meta">@Param("id")</span> <span class="hljs-keyword">int</span> id)</span></span>;
}
UserMapperImpl
复制代码
- 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 mapper;
import pojo.User;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.util.List;
public class UserMapperImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> getUser() {
User user = new User(5,"你好","ok");
insertUser(user);
delUser(5);
SqlSession sqlSession = getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.getUser();
//或者return getSqlSession().getMapper(UserMapper.class).getUser();
}
//插入
public int insertUser(User user) {
return getSqlSession().getMapper(UserMapper.class).insertUser(user);
}
//删除
public int delUser(int id) {
return getSqlSession().getMapper(UserMapper.class).delUser(id);
}
}
UserMapper.xml
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
<!-- 绑定接口 -->
<mapper namespace="mapper.UserMapper">
<select id="getUser" resultType="pojo.User">
select * from mybatis.mybatis
</select>
<span class="hljs-tag"><<span class="hljs-name">insert</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"insertUser"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"pojo.User"</span> ></span>
insert into mybatis.mybatis (id,name,pwd) values (#{id},#{name},#{pwd})
<span class="hljs-tag"></<span class="hljs-name">insert</span>></span>
<span class="hljs-tag"><<span class="hljs-name">delete</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"delUser"</span> <span class="hljs-attr">parameterType</span>=<span class="hljs-string">"_int"</span>></span>
deleteAAAAA from mybatis.mybatis where id = #{id}
<span class="hljs-comment"><!-- deleteAAAAA是故意写错的 --></span>
<span class="hljs-tag"></<span class="hljs-name">delete</span>></span>
</mapper>
resource目录下的 mybatis-config.xml、spring-dao.xml、applicationContext.xml
mybatis-config.xml
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
<!-- configuration -->
<configuration>
<span class="hljs-comment"><!--开启日志--></span>
<span class="hljs-tag"><<span class="hljs-name">settings</span>></span>
<span class="hljs-tag"><<span class="hljs-name">setting</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"logImpl"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"STDOUT_LOGGING"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">settings</span>></span>
<span class="hljs-comment"><!--可以给实体类起别名--></span>
<span class="hljs-tag"><<span class="hljs-name">typeAliases</span>></span>
<span class="hljs-tag"><<span class="hljs-name">package</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"pojo"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">typeAliases</span>></span>
</configuration>
spring-dao.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
- 54
- 55
- 56
<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"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<span class="hljs-comment"><!--data source --></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"datasource"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.jdbc.datasource.DriverManagerDataSource"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"driverClassName"</span>
<span class="hljs-attr">value</span>=<span class="hljs-string">"com.mysql.cj.jdbc.Driver"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"url"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false<span class="hljs-symbol">&amp;</span>useUnicode=true<span class="hljs-symbol">&amp;</span>characterEncoding=utf-8<span class="hljs-symbol">&amp;</span>serverTimezone=Asia/Shanghai"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"username"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"password"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"root"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--sqlSessionFactory--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.mybatis.spring.SqlSessionFactoryBean"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"dataSource"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"datasource"</span> /></span>
<span class="hljs-comment"><!--绑定 mybatis 配置文件--></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"configLocation"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:mybatis-config.xml"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"mapperLocations"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"classpath:mapper/*.xml"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--声明式事务--></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"transactionManager"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"org.springframework.jdbc.datasource.DataSourceTransactionManager"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">constructor-arg</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"datasource"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
<span class="hljs-comment"><!--结合aop实现事务织入--></span>
<span class="hljs-comment"><!--配置事务的通知类--></span>
<span class="hljs-tag"><<span class="hljs-name">tx:advice</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"txAdvice"</span> <span class="hljs-attr">transaction-manager</span>=<span class="hljs-string">"transactionManager"</span>></span>
<span class="hljs-comment"><!--给哪些方法配置事务--></span>
<span class="hljs-comment"><!--新东西:配置事务的传播特性 propagation--></span>
<span class="hljs-tag"><<span class="hljs-name">tx:attributes</span>></span>
<span class="hljs-tag"><<span class="hljs-name">tx:method</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"add"</span> <span class="hljs-attr">propagation</span>=<span class="hljs-string">"REQUIRED"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">tx:method</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"delete"</span> <span class="hljs-attr">propagation</span>=<span class="hljs-string">"REQUIRED"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">tx:method</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"update"</span> <span class="hljs-attr">propagation</span>=<span class="hljs-string">"REQUIRED"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">tx:method</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"query"</span> <span class="hljs-attr">read-only</span>=<span class="hljs-string">"true"</span>/></span>
<span class="hljs-comment"><!-- *号包含上面4个方法:
<tx:method name="*" propagation="REQUIRED"/> --></span>
<span class="hljs-tag"></<span class="hljs-name">tx:attributes</span>></span>
<span class="hljs-tag"></<span class="hljs-name">tx:advice</span>></span>
<span class="hljs-comment"><!--配置事务切入--></span>
<span class="hljs-tag"><<span class="hljs-name">aop:config</span>></span>
<span class="hljs-tag"><<span class="hljs-name">aop:pointcut</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"txpointcut"</span> <span class="hljs-attr">expression</span>=<span class="hljs-string">"execution(* mapper.*.*(..))"</span>/></span>
<span class="hljs-tag"><<span class="hljs-name">aop:advisor</span> <span class="hljs-attr">advice-ref</span>=<span class="hljs-string">"txAdvice"</span> <span class="hljs-attr">pointcut-ref</span>=<span class="hljs-string">"txpointcut"</span>/></span>
<span class="hljs-tag"></<span class="hljs-name">aop:config</span>></span>
</beans>
applicationContext.xml
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
<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">
<span class="hljs-tag"><<span class="hljs-name">import</span> <span class="hljs-attr">resource</span>=<span class="hljs-string">"spring-dao.xml"</span> /></span>
<span class="hljs-tag"><<span class="hljs-name">bean</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"userMapper"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mapper.UserMapperImpl"</span>></span>
<span class="hljs-tag"><<span class="hljs-name">property</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"sqlSessionFactory"</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">"sqlSessionFactory"</span>></span><span class="hljs-tag"></<span class="hljs-name">property</span>></span>
<span class="hljs-tag"></<span class="hljs-name">bean</span>></span>
</beans>
测试类
复制代码
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import mapper.UserMapper;import pojo.User;
public class MyTest7 {
public static void main(String[] args) {
ApplicationContext context = <span class="hljs-keyword">new</span> ClassPathXmlApplicationContext(<span class="hljs-string">"applicationContext.xml"</span>);
UserMapper userMapper = (UserMapper) context.getBean(<span class="hljs-string">"userMapper"</span>);
<span class="hljs-keyword">for</span> (User user : userMapper.getUser()) {
System.out.println(user);
}
}
}
思考:
为什么需要事务?
- 如果不配置事务,可能存在数据提交不一致的情况下;
- 如果不在spring中去配置声明式事务,我们就需要在代码中手动配置事务!
- 事务在项目的开发中非常重要,涉及到数据的一致性和完整性问题!

浙公网安备 33010602011771号