第一步:导入jar包
导入mybatis和spring基本包、Spring-jdbc.jar、Spring-tx.jar、Spring-aop.jar、Mybatis-Spring.jar。
如下所示:
第二步:编写web.xml,加载Spring配置文件
作用:当tomcat加载web.xml时,把Spring配置文件信息存放到application对象WebApplicationContext容器中,WebApplicationContext是ApplicationContext的子接口,防止每次创建一个Servlet,都要重新加载Spring配置文件。
具体代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
//通过上下文参数寻找
<context-param>
<param-name>contextConfigLocation</param-name>
// 加载spring配置文件
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
//封装了一个监听器,帮助加载spring的配置文件
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
第三步:编写applicationContext.xml配置文件
首先:获取数据源,数据库连接,类在spring-jdbc.jar中。
其次:spring帮助创建sqlSessionFactory,根据mybatis运行原理,session在创建时需要连接数据库,所以设置dataSource连接数据库,产生了factory对象
最后:需要扫描器来扫描接口,并创建接口对象。
代码如下:
<?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">
//首先:数据源封装,数据源:获取数据库连接。类在spring-jdbc.jar中
<bean id="dataSouce" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8"></property>
<property name="username" value="root"></property>
<property name="password" value="123"></property>
</bean>
//其次:创建SqlsessionFactory对象,类在mybatis-Spring.jar中
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
//数据库连接信息来源于上面的datasouce
<property name="dataSource" ref="dataSouce"></property>
</bean>
//最后:扫描器,相当于mybatis.xml中mappers下pakeage标签,扫描com.mapper包后会给对应接口创建对象。类在mybatis-Spring.jar中
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
//要扫描哪个包
<property name="basePackage" value="com.mapper"></property>
//因为要产生session,所以和factory产生关系
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
</beans>
整合后代码编写注意事项:
- pojo类正常编写。
- 编写mapper.xml文件时,必须使用接口绑定或者是注解。
- service接口层正常编写。
- serviceImpl实现类中需要声明mapper接口,并生成set()/get()方法。
- spring无法管理servlet,因为通过浏览器访问servlet时,servlet只能由tomcat管理。