代理模式
為什么要學習代理模式,因為AOP的底層機制就是動態代理!
代理模式:
- 靜態代理
- 動態代理
學習aop之前 , 我們要先了解一下代理模式!

1、靜態代理
靜態代理角色分析
- 抽象角色 : 一般使用介面或者抽象類來實作
- 真實角色 : 被代理的角色
- 代理角色 : 代理真實角色 ; 代理真實角色后 , 一般會做一些附屬的操作 .
- 客戶 : 使用代理角色來進行一些操作 .
代碼實作
Rent . java 即抽象角色
//抽象角色:租房
public interface Rent {
public void rent();
}
Host . java 即真實角色
//真實角色: 房東,房東要出租房子
public class Host implements Rent{
public void rent() {
System.out.println("房屋出租");
}
}
Proxy . java 即代理角色
//代理角色:中介
public class Proxy implements Rent {
private Host host;
public Proxy() { }
public Proxy(Host host) {
this.host = host;
}
//租房
public void rent(){
seeHouse();
host.rent();
fare();
}
//看房
public void seeHouse(){
System.out.println("帶房客看房");
}
//收中介費
public void fare(){
System.out.println("收中介費");
}
}
Client . java 即客戶
//客戶類,一般客戶都會去找代理!
public class Client {
public static void main(String[] args) {
//房東要租房
Host host = new Host();
//中介幫助房東
Proxy proxy = new Proxy(host);
//你去找中介!
proxy.rent();
}
}
分析: 在這個程序中,你直接接觸的就是中介,就如同現實生活中的樣子,你看不到房東,但是你依舊 租到了房東的房子通過代理,這就是所謂的代理模式,程式源自于生活,所以學編程的人,一般能夠更 加抽象的看待生活中發生的事情,
2、靜態代理的好處
- 可以使得我們的真實角色更加純粹 . 不再去關注一些公共的事情 .
- 公共的業務由代理來完成 . 實作了業務的分工 ,
- 公共業務發生擴展時變得更加集中和方便 .
缺點 :
- 類多了 , 多了代理類 , 作業量變大了 . 開發效率降低 .
我們想要靜態代理的好處,又不想要靜態代理的缺點,所以 , 就有了動態代理 !
3、靜態代理再理解
練習步驟:
1. 創建一個抽象角色,比如咋們平時做的用戶業務,抽象起來就是增刪改查!
//抽象角色:增刪改查業務
public interface UserService {
void add();
void delete();
void update();
void query();
}
2. 我們需要一個真實物件來完成這些增刪改查操作
//真實物件,完成增刪改查操作的人
public class UserServiceImpl implements UserService {
public void add() {
System.out.println("增加了一個用戶");
}
public void delete() {
System.out.println("洗掉了一個用戶");
}
public void update() {
System.out.println("更新了一個用戶");
}
public void query() {
System.out.println("查詢了一個用戶");
}
}
3. 需求來了,現在我們需要增加一個日志功能,怎么實作!
- 思路1 :在實作類上增加代碼 【麻煩!】
- 思路2:使用代理來做,能夠不改變原來的業務情況下,實作此功能就是最好的了!
4. 設定一個代理類來處理日志! 代理角色
//代理角色,在這里面增加日志的實作
public class UserServiceProxy implements UserService {
private UserServiceImpl userService;
public void setUserService(UserServiceImpl userService) {
this.userService = userService;
}
public void add() {
log("add");
userService.add();
}
public void delete() {
log("delete");
userService.delete();
}
public void update() {
log("update");
userService.update();
}
public void query() {
log("query");
userService.query();
}
public void log(String msg){
System.out.println("執行了"+msg+"方法");
}
}
5. 測驗訪問類:
public class Client {
public static void main(String[] args) {
//真實業務
UserServiceImpl userService = new UserServiceImpl();
//代理類
UserServiceProxy proxy = new UserServiceProxy();
//使用代理類實作日志功能!
proxy.setUserService(userService);
proxy.add();
}
}
OK,到了現在代理模式大家應該都沒有什么問題了,重點大家需要理解其中的思想;
我們在不改變原來的代碼的情況下,實作了對原有功能的增強,這是AOP中最核心的思想
【聊聊AOP:縱向開發,橫向開發】

4、動態代理
- 動態代理的角色和靜態代理的一樣 .
- 動態代理的代理類是動態生成的 . 靜態代理的代理類是我們提前寫好的
- 動態代理分為兩類 : 一類是基于介面動態代理 , 一類是基于類的動態代理
- 基于介面的動態代理----JDK動態代理
- 基于類的動態代理--cglib
- 現在用的比較多的是 javasist 來生成動態代理 . 百度一下javasist
- 我們這里使用JDK的原生代碼來實作,其余的道理都是一樣的!
JDK的動態代理需要了解兩個類
核心 : InvocationHandler 和 Proxy , 打開JDK幫助檔案看看
【InvocationHandler:呼叫處理程式】

Object invoke(Object proxy, 方法 method, Object[] args); //引數 //proxy - 呼叫該方法的代理實體 //method -所述方法對應于呼叫代理實體上的介面方法的實體, 方法物件的宣告類將是該方法宣告的接 口,它可以是代理類繼承該方法的代理介面的超級介面, //args -包含的方法呼叫傳遞代理實體的引數值的物件的陣列,或null如果介面方法沒有引數, 原始 型別的引數包含在適當的原始包裝器類的實體中,例如java.lang.Integer或java.lang.Boolean
【Proxy : 代理】


//生成代理類
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
代碼實作
抽象角色和真實角色和之前的一樣!
Rent . java 即抽象角色
//抽象角色:租房
public interface Rent {
public void rent();
}
Host . java 即真實角色
//真實角色: 房東,房東要出租房子
public class Host implements Rent{
public void rent() {
System.out.println("房屋出租");
}
}
ProxyInvocationHandler. java 即代理角色
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理類,重點是第二個引數,獲取要代理的抽象角色!之前都是一個角色,現在可以代理一類角色
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),rent.getClass().getInterfaces(),this);
}
// proxy : 代理類 method : 代理類的呼叫處理程式的方法物件.
// 處理代理實體上的方法呼叫并回傳結果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//核心:本質利用反射實作!
Object result = method.invoke(rent, args);
fare();
return result;
}
//看房
public void seeHouse(){
System.out.println("帶房客看房");
}
//收中介費
public void fare(){
System.out.println("收中介費");
}
}
Client . java
//租客
public class Client {
public static void main(String[] args) {
//真實角色
Host host = new Host();
//代理實體的呼叫處理程式
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host); //將真實角色放置進去!
Rent proxy = (Rent)pih.getProxy(); //動態生成對應的代理類!
proxy.rent();
}
}
核心:一個動態代理 , 一般代理某一類業務 , 一個動態代理可以代理多個類,代理的是介面!
5、深化理解
我們來使用動態代理實作代理我們后面寫的UserService!
我們也可以撰寫一個通用的動態代理實作的類!所有的代理物件設定為Object即可!
public class ProxyInvocationHandler implements InvocationHandler {
private Object target;
public void setTarget(Object target) {
this.target = target;
}
//生成代理類
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
}
// proxy : 代理類
// method : 代理類的呼叫處理程式的方法物件.
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
log(method.getName());
Object result = method.invoke(target, args);
return result;
}
public void log(String methodName){
System.out.println("執行了"+methodName+"方法");
}
}
測驗!
public class Test {
public static void main(String[] args) {
//真實物件
UserServiceImpl userService = new UserServiceImpl();
//代理物件的呼叫處理程式
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setTarget(userService); //設定要代理的物件
UserService proxy = (UserService)pih.getProxy(); //動態生成代理類!
proxy.delete();
}
}
【測驗,增刪改查,查看結果】
6、動態代理的好處
靜態代理有的它都有,靜態代理沒有的,它也有!
- 可以使得我們的真實角色更加純粹 . 不再去關注一些公共的事情 .
- 公共的業務由代理來完成 . 實作了業務的分工 ,
- 公共業務發生擴展時變得更加集中和方便 .
- 一個動態代理 , 一般代理某一類業務
- 一個動態代理可以代理多個類,代理的是介面!
AOP
1 什么是AOP
AOP(Aspect Oriented Programming)意為:面向切面編程,通過預編譯方式和運行期動態代理實作 程式功能的統一維護的一種技術,AOP是OOP的延續,是軟體開發中的一個熱點,也是Spring框架中的 一個重要內容,是函式式編程的一種衍生范型,利用AOP可以對業務邏輯的各個部分進行隔離,從而使 得業務邏輯各部分之間的耦合度降低,提高程式的可重用性,同時提高了開發的效率,

2 Aop在Spring中的作用
提供宣告式事務;允許用戶自定義切面
- 橫切關注點:跨越應用程式多個模塊的方法或功能,即是,與我們業務邏輯無關的,但是我們需要 關注的部分,就是橫切關注點,如日志 , 安全 , 快取 , 事務等等 ....
- 切面(ASPECT):橫切關注點 被模塊化 的特殊物件,即,它是一個類,
- 通知(Advice):切面必須要完成的作業,即,它是類中的一個方法,
- 目標(Target):被通知物件,
- 代理(Proxy):向目標物件應用通知之后創建的物件,
- 切入點(PointCut):切面通知 執行的 “地點”的定義,
- 連接點(JointPoint):與切入點匹配的執行點,

SpringAOP中,通過Advice定義橫切邏輯,Spring中支持5種型別的Advice:

即 Aop 在 不改變原有代碼的情況下 , 去增加新的功能 .
3 使用Spring實作Aop
【重點】使用AOP織入,需要匯入一個依賴包!
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
第一種方式
通過 Spring API 實作
首先撰寫我們的業務介面和實作類
public interface UserService {
public void add();
public void delete();
public void update();
public void search();
}
public class UserServiceImpl implements UserService{
@Override
public void add() {
System.out.println("增加用戶");
}
@Override
public void delete() {
System.out.println("洗掉用戶");
}
@Override
public void update() {
System.out.println("更新用戶");
}
@Override
public void search() {
System.out.println("查詢用戶");
}
}
然后去寫我們的增強類 , 我們撰寫兩個 , 一個前置增強 一個后置增強
public class Log implements MethodBeforeAdvice {
//method : 要執行的目標物件的方法
//objects : 被呼叫的方法的引數
//Object : 目標物件
@Override
public void before(Method method, Object[] objects, Object o) throws Throwable {
System.out.println( o.getClass().getName() + "的" + method.getName()+ "方法被執行了");
}
}
public class AfterLog implements AfterReturningAdvice {
//returnValue 回傳值
//method被呼叫的方法
//args 被呼叫的方法的物件的引數
//target 被呼叫的目標物件
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("執行了" + target.getClass().getName()+"的"+method.getName()+"方法,"+"回傳值:"+returnValue);
}
}
最后去spring的檔案中注冊 , 并實作aop切入實作 , 注意匯入約束
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--注冊bean--> <bean id="userService" class="com.hang.service.UserServiceImpl"/> <bean id="log" class="com.hang.log.Log"/> <bean id="afterLog" class="com.hang.log.AfterLog"/> <!--aop的配置--> <aop:config> <!--切入點 expression:運算式匹配要執行的方法--> <aop:pointcut id="pointcut" expression="execution(* com.hang.service.UserServiceImpl.*(..))"/> <!--執行環繞; advice-ref執行方法 . pointcut-ref切入點--> <aop:advisor advice-ref="log" pointcut-ref="pointcut"/> <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/> </aop:config> </beans>
測驗
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService)
context.getBean("userService");
userService.search();
}
}
Aop的重要性 : 很重要 . 一定要理解其中的思路 , 主要是思想的理解這一塊 .
Spring的Aop就是將公共的業務 (日志 , 安全等) 和領域業務結合起來 , 當執行領域業務時 , 將會把公共業 務加進來 . 實作公共業務的重復利用 . 領域業務更純粹 , 程式猿專注領域業務 , 其本質還是動態代理 .
第二種方式
自定義類來實作Aop
目標業務類不變依舊是userServiceImpl
第一步 : 寫我們自己的一個切入類
public class DiyPointcut {
public void before(){
System.out.println("---------方法執行前---------");
}
public void after(){
System.out.println("---------方法執行后---------");
}
}
去spring中配置
<!--第二種方式自定義實作--> <!--注冊bean--> <bean id="diy" />
<!--aop的配置--> <aop:config> <!--第二種方式:使用AOP的標簽實作--> <aop:aspect ref="diy"> <aop:pointcut id="diyPonitcut" expression="execution(* com.kuang.service.UserServiceImpl.*(..))"/> <aop:before pointcut-ref="diyPonitcut" method="before"/> <aop:after pointcut-ref="diyPonitcut" method="after"/> </aop:aspect> </aop:config>
測驗:
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserService userService = (UserService)
context.getBean("userService");
userService.add();
}
}
第三種方式
使用注解實作
第一步:撰寫一個注解實作的增強類
package com.hang.config;
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;
@Aspect public class AnnotationPointcut { @Before("execution(* com.kuang.service.UserServiceImpl.*(..))") public void before(){ System.out.println("---------方法執行前---------"); } @After("execution(* com.kuang.service.UserServiceImpl.*(..))") public void after(){ System.out.println("---------方法執行后---------"); } @Around("execution(* com.kuang.service.UserServiceImpl.*(..))") public void around(ProceedingJoinPoint jp) throws Throwable { System.out.println("環繞前"); System.out.println("簽名:"+jp.getSignature()); //執行目標方法proceed Object proceed = jp.proceed(); System.out.println("環繞后"); System.out.println(proceed); } }
第二步:在Spring組態檔中,注冊bean,并增加支持注解的配置
<!--第三種方式:注解實作--> <bean id="annotationPointcut" class="com.kuang.config.AnnotationPointcut"/> <aop:aspectj-autoproxy/>
aop:aspectj-autoproxy:說明

整合Mybatis
步驟:
1) 匯入相關jar包
1. junit
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency>
2. mybatis
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.2</version> </dependency>
3. mysql-connector-java
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency>
4. spring相關
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.1.10.RELEASE</version> </dependency>
5. aspectJ AOP 織入器
<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.4</version> </dependency>
6. mybatis-spring整合包 【重點】
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency>
7. 配置Maven靜態資源過濾問題!
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2) 撰寫組態檔
3) 代碼實作
回憶MyBatis
撰寫pojo物體類
package com.hang.pojo;
public class User {
private int id; //id
private String name; //姓名
private String pwd; //密碼
}
實作mybatis的組態檔
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "https://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis?useUnicode=true&characterEncoding=utf8&useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <package name="com.hang.dao"/> </mappers> </configuration>
UserDao介面撰寫
public interface UserMapper {
public List<User> selectUser();
}
介面對應的Mapper映射檔案
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.kuang.dao.UserMapper"> <select id="selectUser" resultType="User"> select * from user </select> </mapper>
測驗類
@Test
public void selectUser() throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.selectUser();
for (User user: userList){
System.out.println(user);
}
sqlSession.close();
}
MyBatis-Spring學習
引入Spring之前需要了解mybatis-spring包中的一些重要類;
http://www.mybatis.org/spring/zh/index.html

什么是 MyBatis-Spring?
MyBatis-Spring 會幫助你將 MyBatis 代碼無縫地整合到 Spring 中,
知識基礎
在開始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 這兩個框架和有關它們的術語,這 很重要
MyBatis-Spring 需要以下版本:

如果使用 Maven 作為構建工具,僅需要在 pom.xml 中加入以下代碼即可:
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.2</version> </dependency>
要和 Spring 一起使用 MyBatis,需要在 Spring 應用背景關系中定義至少兩樣東西:一個 SqlSessionFactory 和至少一個資料映射器類,
在 MyBatis-Spring 中,可使用 SqlSessionFactoryBean 來創建 SqlSessionFactory , 要配置 這個工廠 bean,只需要把下面代碼放在 Spring 的 XML 組態檔中:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>
注意: SqlSessionFactory 需要一個 DataSource (資料源), 這可以是任意的 DataSource ,只需要和配置其它 Spring 資料庫連接一樣配置它就可以了,
在基礎的 MyBatis 用法中,是通過 SqlSessionFactoryBuilder 來創建 SqlSessionFactory 的, 而在 MyBatis-Spring 中,則使用 SqlSessionFactoryBean 來創建,
在 MyBatis 中,你可以使用 SqlSessionFactory 來創建 SqlSession ,一旦你獲得一個 session 之后,你可以使用它來執行映射了的陳述句,提交或回滾連接,最后,當不再需要它的時候,你 可以關閉 session,
SqlSessionFactory 有一個唯一的必要屬性:用于 JDBC 的 DataSource ,這可以是任意的 DataSource 物件,它的配置方法和其它 Spring 資料庫連接是一樣的,
一個常用的屬性是 configLocation ,它用來指定 MyBatis 的 XML 組態檔路徑,它在需要修改 MyBatis 的基礎配置非常有用,通常,基礎配置指的是<settings> 或 <typeAliases>元素,
需要注意的是,這個組態檔并不需要是一個完整的 MyBatis 配置,確切地說,任何環境配置 ( <environments>),資料源(<DataSource> )和 MyBatis 的事務管理器 ( <transactionManager>)都會被忽略, SqlSessionFactoryBean 會創建它自有的 MyBatis 環境配置( Environment ),并按要求設定自定義環境的值,
SqlSessionTemplate 是 MyBatis-Spring 的核心,作為 SqlSession 的一個實作,這意味著可 以使用它無縫代替你代碼中已經在使用的 SqlSession ,
模板可以參與到 Spring 的事務管理中,并且由于其是執行緒安全的,可以供多個映射器類使用,你應該總 是用 SqlSessionTemplate 來替換 MyBatis 默認的 DefaultSqlSession 實作,在同一應用程 序中的不同類之間混雜使用可能會引起資料一致性的問題,
可以使用 SqlSessionFactory 作為構造方法的引數來創建 SqlSessionTemplate 物件,
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory" /> </bean>
現在,這個 bean 就可以直接注入到你的 DAO bean 中了,你需要在你的 bean 中添加一個 SqlSession 屬性,就像下面這樣:
public class UserDaoImpl implements UserDao {
private SqlSession sqlSession;
public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}
public User getUser(String userId) {
return sqlSession.getMapper...;
}
}
按下面這樣,注入 SqlSessionTemplate :
<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl"> <property name="sqlSession" ref="sqlSession" /> </bean>
整合實作一
1. 引入Spring組態檔beans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>
2. 配置資料源替換mybaits的資料源
<!--配置資料源:資料源有非常多,可以使用第三方的,也可使使用Spring的--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8"/> <property name="username" value="root"/> <property name="password" value="123456"/> </bean>
3. 配置SqlSessionFactory,關聯MyBatis
<!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--關聯Mybatis--> <property name="configLocation" value="classpath:mybatisconfig.xml"/> <property name="mapperLocations" value="classpath:com/hang/dao/*.xml"/> </bean>
4. 注冊sqlSessionTemplate,關聯sqlSessionFactory;
<!--注冊sqlSessionTemplate , 關聯sqlSessionFactory--> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <!--利用構造器注入--> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean>
5. 增加Dao介面的實作類;私有化sqlSessionTemplate
public class UserDaoImpl implements UserMapper {
//sqlSession不用我們自己創建了,Spring來管理
private SqlSessionTemplate sqlSession;
public void setSqlSession(SqlSessionTemplate sqlSession) {
this.sqlSession = sqlSession;
}
public List<User> selectUser() {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
return mapper.selectUser();
}
}
6. 注冊bean實作
<bean id="userDao" class="com.kuang.dao.UserDaoImpl"> <property name="sqlSession" ref="sqlSession"/> </bean>
7. 測驗
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
結果成功輸出!現在我們的Mybatis組態檔的狀態!發現都可以被Spring整合!
整合實作二
mybatis-spring1.2.3版以上的才有這個 .
官方檔案截圖 :
dao繼承Support類 , 直接利用 getSqlSession() 獲得 , 然后直接注入SqlSessionFactory . 比起方式1 , 不 需要管理SqlSessionTemplate , 而且對事務的支持更加友好 . 可跟蹤原始碼查看

測驗:
1. 將我們上面寫的UserDaoImpl修改一下
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
public List<User> selectUser() {
UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
return mapper.selectUser();
}
}
2. 修改bean的配置
<bean id="userDao" class="com.kuang.dao.UserDaoImpl"> <property name="sqlSessionFactory" ref="sqlSessionFactory" /> </bean>
3. 測驗
@Test
public void test2(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
UserMapper mapper = (UserMapper) context.getBean("userDao");
List<User> user = mapper.selectUser();
System.out.println(user);
}
總結 : 整合到spring中以后可以完全不要mybatis的組態檔,除了這些方式可以實作整合之外,我們還 可以使用注解來實作,這個等我們后面學習SpringBoot的時候還會測驗整合!
本文來自博客園,作者:腹白,轉載請注明原文鏈接:https://www.cnblogs.com/wyh518/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/544249.html
標籤:Java
上一篇:微軟出品自動化神器【Playwright+Java】系列(九)多執行緒、重定向、彈出新視窗、截圖、新頁面、錄制、頁面物件模式操作
