Spring与Mybatis整合的MapperScannerConfigurer怎么用

发布时间:2021-12-30 09:30:03 作者:小新
来源:亿速云 阅读:470
# Spring与Mybatis整合的MapperScannerConfigurer怎么用

## 一、前言

在Java企业级应用开发中,Spring框架和MyBatis持久层框架的组合被广泛使用。Spring提供了强大的IoC容器和AOP支持,而MyBatis则简化了数据库操作。将两者整合使用时,`MapperScannerConfigurer`是一个关键组件,它能够自动扫描和注册MyBatis的Mapper接口,极大地简化了开发配置。

本文将详细介绍`MapperScannerConfigurer`的使用方法、原理分析、常见问题及解决方案,并通过完整示例演示如何在实际项目中应用。

## 二、MapperScannerConfigurer概述

### 2.1 什么是MapperScannerConfigurer

`MapperScannerConfigurer`是MyBatis-Spring整合包中提供的一个类,位于`org.mybatis.spring.mapper`包下。它的主要功能是:

1. 自动扫描指定包路径下的Mapper接口
2. 将这些接口注册为Spring容器中的Bean
3. 为每个Mapper接口创建代理对象

### 2.2 为什么需要MapperScannerConfigurer

在没有使用`MapperScannerConfigurer`之前,我们需要手动为每个Mapper接口配置`MapperFactoryBean`:

```xml
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="com.example.dao.UserMapper"/>
  <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

当项目中有大量Mapper接口时,这种配置方式会非常繁琐。MapperScannerConfigurer通过自动扫描的方式解决了这个问题。

三、环境准备

3.1 所需依赖

在开始之前,确保你的项目中包含以下依赖:

<!-- Spring核心依赖 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.18</version>
</dependency>

<!-- MyBatis核心依赖 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>

<!-- MyBatis-Spring整合包 -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.7</version>
</dependency>

<!-- 数据库驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.28</version>
</dependency>

<!-- 连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.8</version>
</dependency>

3.2 项目结构

典型的项目结构如下:

src/main/java
    ├── com.example
    │   ├── config
    │   │   ├── MyBatisConfig.java
    │   │   └── SpringConfig.java
    │   ├── dao
    │   │   ├── UserMapper.java
    │   │   └── ProductMapper.java
    │   ├── entity
    │   │   ├── User.java
    │   │   └── Product.java
    │   └── service
    │       └── UserService.java
src/main/resources
    ├── mybatis
    │   ├── UserMapper.xml
    │   └── ProductMapper.xml
    └── application.properties

四、XML配置方式

4.1 基本配置

在Spring的XML配置文件中配置MapperScannerConfigurer

<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 id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 数据源配置 -->
    </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:mybatis/*.xml"/>
    </bean>

    <!-- 配置MapperScannerConfigurer -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.dao"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
</beans>

4.2 配置属性详解

MapperScannerConfigurer支持以下重要属性:

属性名 说明 默认值
basePackage 指定要扫描的包路径,多个包可以用逗号或分号分隔 无,必须指定
sqlSessionFactoryBeanName 指定SqlSessionFactory的Bean名称 sqlSessionFactory
sqlSessionTemplateBeanName 指定SqlSessionTemplate的Bean名称
annotationClass 指定要扫描的注解类型 无,扫描所有接口
markerInterface 指定要扫描的父接口
processPropertyPlaceHolders 是否处理属性占位符 true

4.3 多包扫描配置

如果需要扫描多个包,可以使用逗号或分号分隔:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.dao,com.example.other.dao"/>
</bean>

五、Java配置方式

5.1 使用@MapperScan注解

Spring提供了更简洁的@MapperScan注解方式:

@Configuration
@MapperScan("com.example.dao")
public class MyBatisConfig {
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(
            new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/*.xml"));
        return sessionFactory.getObject();
    }
}

5.2 自定义配置

@MapperScan支持丰富的配置选项:

@Configuration
@MapperScan(
    basePackages = "com.example.dao",
    sqlSessionFactoryRef = "sqlSessionFactory",
    annotationClass = Repository.class,
    markerInterface = BaseMapper.class
)
public class MyBatisConfig {
    // 其他配置
}

六、高级配置与定制

6.1 自定义MapperFactoryBean

如果需要自定义Mapper代理的创建过程,可以继承MapperFactoryBean

public class CustomMapperFactoryBean<T> extends MapperFactoryBean<T> {
    public CustomMapperFactoryBean(Class<T> mapperInterface) {
        super(mapperInterface);
    }
    
    @Override
    protected void checkDaoConfig() {
        super.checkDaoConfig();
        // 自定义逻辑
    }
}

然后在配置中指定:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.dao"/>
    <property name="mapperFactoryBeanClass" value="com.example.config.CustomMapperFactoryBean"/>
</bean>

6.2 使用SqlSessionTemplate

如果需要更精细控制SQL会话,可以配置SqlSessionTemplate

@Bean
public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    return new SqlSessionTemplate(sqlSessionFactory);
}

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer scanner = new MapperScannerConfigurer();
    scanner.setBasePackage("com.example.dao");
    scanner.setSqlSessionTemplateBeanName("sqlSessionTemplate");
    return scanner;
}

七、常见问题与解决方案

7.1 Mapper接口未被扫描到

问题现象:Spring容器中没有注册Mapper接口的Bean。

可能原因: 1. basePackage配置错误 2. Mapper接口不在指定包路径下 3. 缺少@Mapper注解或未配置annotationClass

解决方案: 1. 检查basePackage路径是否正确 2. 确认Mapper接口的包路径 3. 在接口上添加@Mapper注解或配置annotationClass

7.2 出现”BeanCreationException”

问题现象:启动时抛出BeanCreationException,提示无法创建Mapper Bean。

可能原因: 1. 缺少对应的XML映射文件 2. SQL语句配置错误 3. 数据库连接问题

解决方案: 1. 检查mapperLocations配置 2. 验证XML映射文件中的SQL语句 3. 检查数据库连接配置

7.3 事务不生效

问题现象:Mapper中的操作没有在事务中执行。

解决方案: 1. 确保配置了事务管理器 2. 在Service层添加@Transactional注解 3. 检查AOP配置是否正确

@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
}

八、最佳实践

8.1 项目结构组织建议

  1. 将Mapper接口与对应的XML映射文件放在相同模块中
  2. 使用明确的包命名,如com.example.dao
  3. 为不同的业务模块划分不同的Mapper包

8.2 性能优化建议

  1. 合理配置连接池参数
  2. 使用二级缓存时注意缓存策略
  3. 批量操作使用SqlSession的批量模式

8.3 安全注意事项

  1. 防止SQL注入,使用#{}代替${}
  2. 敏感数据查询添加权限控制
  3. 定期检查Mapper XML中的SQL语句

九、完整示例

9.1 实体类

public class User {
    private Long id;
    private String username;
    private String password;
    // getters and setters
}

9.2 Mapper接口

public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User selectById(Long id);
    
    @Insert("INSERT INTO user(username, password) VALUES(#{username}, #{password})")
    int insert(User user);
    
    // 其他方法
}

9.3 Service层

@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Transactional
    public User getUserById(Long id) {
        return userMapper.selectById(id);
    }
    
    // 其他业务方法
}

9.4 主配置类

@Configuration
@ComponentScan("com.example")
@MapperScan("com.example.dao")
@PropertySource("classpath:application.properties")
public class AppConfig {
    
    @Bean
    public DataSource dataSource() {
        // 数据源配置
    }
    
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
        // SqlSessionFactory配置
    }
}

十、总结

MapperScannerConfigurer是Spring与MyBatis整合中的关键组件,它通过自动扫描的方式简化了Mapper接口的注册过程。本文详细介绍了:

  1. MapperScannerConfigurer的基本原理和作用
  2. XML和Java两种配置方式
  3. 高级定制方法和常见问题解决方案
  4. 实际项目中的最佳实践

通过合理使用MapperScannerConfigurer,可以大大提高开发效率,减少样板代码,使开发者更专注于业务逻辑的实现。

参考资料

  1. MyBatis官方文档: https://mybatis.org/mybatis-3/zh/index.html
  2. MyBatis-Spring整合文档: https://mybatis.org/spring/zh/index.html
  3. Spring Framework文档: https://spring.io/projects/spring-framework

”`

推荐阅读:
  1. Spring整合Mybatis
  2. Spring Boot 整合 MyBatis

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring mybatis mapperscannerconfigurer

上一篇:如何通过map操作看RDD的Map过程

下一篇:IdentityServer4实战中怎么与API单项目整合

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》