Spring Boot 集成Mybatis,@MapperScan不能解析占位符问题

本文介绍了在Spring Boot集成Mybatis时遇到的@MapperScan无法解析Application.properties中占位符的问题。原因是注册类在初始化时未使用EnvironmentCapable的registry,导致占位符无法正确解析。解决方案是创建自定义的ExpandMapperScan和ExpandMapperScannerRegistrar,通过手动注入环境来确保占位符的解析。具体实现细节和源码跟踪未在本文详述。
摘要由CSDN通过智能技术生成

问题描述

Mybatis的@MapperScan中的basePackages属性值,只能获取到系统的占位符,不能获取到Application.properties定义的占位符

原因

@MapperScan 的处理类 MapperScannerRegistrar
MapperScannerRegistrar.registerBeanDefinitions()
-> new ClassPathMapperScanner(registry)
-> super(registry, false)
-> this(registry, useDefaultFilters, getOrCreateEnvironment(registry))
->

private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        if (registry instanceof EnvironmentCapable) {
            return ((EnvironmentCapable) registry).getEnvironment();
        }
        return new StandardEnvironment();
    }

这里的registry 不是EnvironmentCapable,所以生成了一个新的环境类

解决

创建ExpandMapperScan

@MapperScan 的属性一样只是改变 @Import(ExpandMapperScannerRegistrar.class)

import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.annotation.Import;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(ExpandMapperScannerRegistrar.class)
public @interface ExpandMapperScan {

    /**
     * Alias for the {
   @link #basePackages()} attribute. Allows for more concise
     * annotation declarations e.g.:
     * {
   @code @EnableMyBatisMapperScanner("org.my.pkg")} instead of {
   @code
     * @EnableMyBatisMapperScanner(basePackages= "org.my.pkg"})}.
     */
    String[] value() default {};

    /**
     * Base packages to scan for MyBatis interfaces. Note that only interfaces
     * with at least one method will be registered; concrete classes will be
     * ignored.
     */
    String[] basePackages() default {};

    /**
     * Type-safe al
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值