背景
在使用Mybatis-plus时,经常需要定义MybatisScan 以扫描dao包
@Configuration
@MapperScan(basepackage="com....mapper")
public class MybatisPlusConfiguration{
}
注解的定义
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
public @interface MapperScan
定义中引入了MapperScannerRegistrar类,此类实现了ImportBeanDefinitionRegistrar 这个接口
其实现方法registerBeanDefinitions 中定义
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MapperScannerConfigurer.class);
从注解三步曲中可以看到
- 定义注解MapperScan
- 解析注解MapperScannerConfigurer
- 使用注解(MybatisPlusConfiguration配置类)
具体解析方法可以详看MapperScannerConfigurer.postProcessBeanDefinitionRegistry
其定义了 ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
并将默认的参数注入其中,以此扫描指定的包
如
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
if (this.processPropertyPlaceHolders) {
processPropertyPlaceHolders();
}
ClassPathMapperScanner scanner = new ClassPathMapperScanner(registry);
scanner.setAddToConfig(this.addToConfig);
scanner.setAnnotationClass(this.annotationClass);
scanner.setMarkerInterface(this.markerInterface);
scanner.setSqlSessionFactory(this.sqlSessionFactory);
scanner.setSqlSessionTemplate(this.sqlSessionTemplate);
scanner.setSqlSessionFactoryBeanName(this.sqlSessionFactoryBeanName);
scanner.setSqlSessionTemplateBeanName(this.sqlSessionTemplateBeanName);
scanner.setResourceLoader(this.applicationContext);
scanner.setBeanNameGenerator(this.nameGenerator);
scanner.setMapperFactoryBeanClass(this.mapperFactoryBeanClass);
if (StringUtils.hasText(lazyInitialization)) {
scanner.setLazyInitialization(Boolean.valueOf(lazyInitialization));
}
if (StringUtils.hasText(defaultScope)) {
scanner.setDefaultScope(defaultScope);
}
scanner.registerFilters();
scanner.scan(
StringUtils.tokenizeToStringArray(this.basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
}
总结
针对框架的注解,我们一般是使用角色,其定义和解析一般是框架已完成。若想了解实现逻辑,可追踪其实现源码。