Spring 整合 Mybatis、Junit
Spring 集成 Junit
1、使用 @ExtendWith 注解替换原来的运行期 注意:原来的 Junit4 使用的是 @RunWith(SpringJUnit4ClassRunner.class)
2、使用 @ContextConfiguration 指定配置文件或配置类
3、使用 @Autowired 注入需要测试的对象
导入依赖,除了 Junit 外,Spring 也需要导入一个 Spring-test
<!-- 注意这里使用的是 Junit5 与 Junit4 是有区别的 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.5.RELEASE</version>
<scope>test</scope>
</dependency>
<!-- 原来的 Junit 包已经迁移到这里了 -->
<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.6.2</version>
<scope>test</scope>
</dependency>
注:在 SpringBoot 里这个单元测试被集成了
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
使用例
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:applicationConfiguration.xml")
// 如果是使用注解配置的则:@ContextConfiguration(classes = {applicationConfiguration.class})
class UserServiceTest {
@Autowired
private UserService userService;
@Test
public void test(){
userService.sayHello();
}
}
坑:报错 Error creating bean with name 'mvcContentNegotiationManager':
单元测试时缺少环境
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
MyBatis-spring
概述
MyBatis-Spring 就是 MyBatis 写的一个在 Spring 环境下工作的依赖包,它可以让 MyBatis 直接使用到 Spring 的事务管理。
创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。
配置DataSource
使用 Spring 的数据源替换 MyBatis 的配置c3p0、dbcp、druid
原本是在 MyBatis 的 environments 里面配置的,而到了 Spring 之后可以直接把 DataSource Bean 交给 Spring 来管理,MyBatis 要用的话,Spring 会自动注入这个 DataSource 到 MyBatis 里面去
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="url" value="jdbc:mysql://localhost:3306/studyJDBC?useUnicode=true& characterEncoding=utf8&useSSL=true&useServerPrepStmts=true"/>
<property name="password" value="123"/>
</bean>
读取 Properties 文件
除了像上面那样直接写死在 xml 文件里,还可以单独拿出一个 Properties 来写配置 DataSource 配置信息
<!-- 加载 properties 文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.username}"/>
<property name="url" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
使用 XML 配置
配置 SqlSessionFactory
配置这个工厂 bean
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--绑定MyBatis的配置文件,这样就能结合使用mybatis-config.xml了-->
<property name="configuration" value="classpath:mybatis-config.xml"/>
<!--也可以在这里绑定Mapper-->
<property name="mapperLocations" value="classpath:com/alsritter/mapper/*.xml"/>
</bean>
配置 Mapper
假设定义了一个如下的 mapper 接口:
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{userId}")
User getUser(@Param("userId") String userId);
}
那么可以通过 MapperFactoryBean 将接口加入到 Spring 中: 注意:MapperFactoryBean实现了 FactoryBean 这个接口,所以可以动态生成一个 Mapper 实例对象
这个 FactoryBean 接口是 Spring 专门提供用来实现工厂模式的
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatis.spring.sample.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
使用例
public interface BookMapper {
// 查询全部书
@Select("select * from books")
List<Book> getAllBooks();
}
<?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">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="url"
value="jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf8&useSSL=true&useServerPrepStmts=true"/>
<property name="password" value="123"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperFactoryBean" id="bookMapper">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="mapperInterface" value="com.alsritter.dao.BookMapper"/>
</bean>
</beans>
在单元测试里使用上面创建的 Mapper
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
BookMapper bookMapper = context.getBean("bookMapper", BookMapper.class);
List<Book> allBooks = bookMapper.getAllBooks();
allBooks.forEach(System.out::println);
}
}