Spring AOP及整合Mybatis
代理模式
为什么要学习代理模式,因为AOP的底层机制就是动态代理!
代理模式:
- 静态代理
- 动态代理
学习aop之前 , 我们要先了解一下代理模式!
1、静态代理
静态代理角色分析
- 抽象角色 : 一般使用接口或者抽象类来实现
- 真实角色 : 被代理的角色
- 代理角色 : 代理真实角色 ; 代理真实角色后 , 一般会做一些附属的操作 .
- 客户 : 使用代理角色来进行一些操作 .
代码实现
Rent . java 即抽象角色
1 2 3 4 | //抽象角色:租房 public interface Rent { public void rent(); } |
Host . java 即真实角色
1 2 3 4 5 6 | //真实角色: 房东,房东要出租房子 public class Host implements Rent{ public void rent() { System.out.println( "房屋出租" ); } } |
Proxy . java 即代理角色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //代理角色:中介 public class Proxy implements Rent { private Host host;<br> 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 即客户
1 2 3 4 5 6 7 8 9 10 11 | //客户类,一般客户都会去找代理! public class Client { public static void main(String[] args) { //房东要租房 Host host = new Host(); //中介帮助房东 Proxy proxy = new Proxy(host); //你去找中介! proxy.rent(); } } |
分析: 在这个过程中,你直接接触的就是中介,就如同现实生活中的样子,你看不到房东,但是你依旧 租到了房东的房子通过代理,这就是所谓的代理模式,程序源自于生活,所以学编程的人,一般能够更 加抽象的看待生活中发生的事情。
2、静态代理的好处
- 可以使得我们的真实角色更加纯粹 . 不再去关注一些公共的事情 .
- 公共的业务由代理来完成 . 实现了业务的分工 ,
- 公共业务发生扩展时变得更加集中和方便 .
缺点 :
- 类多了 , 多了代理类 , 工作量变大了 . 开发效率降低 .
我们想要静态代理的好处,又不想要静态代理的缺点,所以 , 就有了动态代理 !
3、静态代理再理解
练习步骤:
1. 创建一个抽象角色,比如咋们平时做的用户业务,抽象起来就是增删改查!
1 2 3 4 5 6 7 | //抽象角色:增删改查业务 public interface UserService { void add(); void delete(); void update(); void query(); } |
2. 我们需要一个真实对象来完成这些增删改查操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | //真实对象,完成增删改查操作的人 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. 设置一个代理类来处理日志! 代理角色
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 | //代理角色,在这里面增加日志的实现 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. 测试访问类:
1 2 3 4 5 6 7 8 9 10 11 | 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:调用处理程序】
1 2 3 4 5 6 7 | Object invoke(Object proxy, 方法 method, Object[] args); //参数 //proxy - 调用该方法的代理实例 //method -所述方法对应于调用代理实例上的接口方法的实例。 方法对象的声明类将是该方法声明的接 口,它可以是代理类继承该方法的代理接口的超级接口。 //args -包含的方法调用传递代理实例的参数值的对象的阵列,或null如果接口方法没有参数。 原始 类型的参数包含在适当的原始包装器类的实例中,例如java.lang.Integer或java.lang.Boolean |
【Proxy : 代理】
1 2 3 4 | //生成代理类 public Object getProxy(){ return Proxy.newProxyInstance( this .getClass().getClassLoader(),rent.getClass().getInterfaces(), this ); } |
代码实现
抽象角色和真实角色和之前的一样!
Rent . java 即抽象角色
1 2 3 4 | //抽象角色:租房 public interface Rent { public void rent(); } |
Host . java 即真实角色
1 2 3 4 5 6 | //真实角色: 房东,房东要出租房子 public class Host implements Rent{ 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 | 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
1 2 3 4 5 6 7 8 9 10 11 12 | //租客 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即可!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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+ "方法" ); } } |
测试!
1 2 3 4 5 6 7 8 9 10 11 | 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织入,需要导入一个依赖包!
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> |
第一种方式
通过 Spring API 实现
首先编写我们的业务接口和实现类
1 2 3 4 5 6 | public interface UserService { public void add(); public void delete(); public void update(); public void search(); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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( "查询用户" ); } } |
然后去写我们的增强类 , 我们编写两个 , 一个前置增强 一个后置增强
1 2 3 4 5 6 7 8 9 | 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()+ "方法被执行了" ); } } |
1 2 3 4 5 6 7 8 9 10 | 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>
测试
1 2 3 4 5 6 7 8 9 | 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
第一步 : 写我们自己的一个切入类
1 2 3 4 5 6 7 8 | public class DiyPointcut { public void before(){ System.out.println( "---------方法执行前---------" ); } public void after(){ System.out.println( "---------方法执行后---------" ); } } |
去spring中配置
1 2 3 4 5 6 7 8 9 10 11 12 | <!--第二种方式自定义实现--> <!--注册bean--> <bean id= "diy" class = "com.kuang.config.DiyPointcut" /><br> <!--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> |
测试:
1 2 3 4 5 6 7 8 9 | public class MyTest { @Test public void test(){ ApplicationContext context = new ClassPathXmlApplicationContext( "beans.xml" ); UserService userService = (UserService) context.getBean( "userService" ); userService.add(); } } |
第三种方式
使用注解实现
第一步:编写一个注解实现的增强类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.hang.config;<br> 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;<br> @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
1 2 3 4 5 | <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version> 4.12 </version> </dependency> |
2. mybatis
1 2 3 4 5 | <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version> 3.5 . 2 </version> </dependency> |
3. mysql-connector-java
1 2 3 4 5 | <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version> 5.1 . 47 </version> </dependency> |
4. spring相关
1 2 3 4 5 6 7 8 9 10 | <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 织入器
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> |
6. mybatis-spring整合包 【重点】
1 2 3 4 5 | <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version> 2.0 . 2 </version> </dependency> |
7. 配置Maven静态资源过滤问题!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <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实体类
1 2 3 4 5 6 | 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接口编写
1 2 3 | 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>
测试类
1 2 3 4 5 6 7 8 9 10 11 12 13 | @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();<br> UserMapper mapper = sqlSession.getMapper(UserMapper. class ); <br> 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 属性,就像下面这样:
1 2 3 4 5 6 7 8 9 | 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
1 2 3 4 5 6 7 8 9 10 11 | 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. 测试
1 2 3 4 5 6 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修改一下
1 2 3 4 5 6 | 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. 测试
1 2 3 4 5 6 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); } |
总结 : 整合到spring中以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还 可以使用注解来实现,这个等我们后面学习SpringBoot的时候还会测试整合!
本文来自博客园,作者:腹白,转载请注明原文链接:https://www.cnblogs.com/wyh518/
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 没有源码,如何修改代码逻辑?
· NetPad:一个.NET开源、跨平台的C#编辑器
· 面试官:你是如何进行SQL调优的?