问题描述
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