对于我们 java 来说,接口是不能被实例化的。而且接口的所有方法都是public的。
可是为什么 Mybaits 的mapper 接口,可以直接 @Autowired 注入 使用?
接下来看看Mybatis 是如何做的。
基于SpringBoot 的 @MapperScan 注解入手,分析。
带着问题分析代码:Mybatis 的mapper接口,是怎么被扫描的?
mapper接口是如何被实例化,然后可以使用@Autowired注入?
@MapperScan
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(MapperScannerRegistrar.class)
@Repeatable(MapperScans.class)
public @interface MapperScan {
// 在使用MapperScan中,扫描包的路径。 // 填写的是 mapper 接口所在包名,对该value值下的所有文件进行扫描 String[] value() default {};
String[] basePackages() default {};
Class>[] basePackageClasses() default {};
Class extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class;
Class extends Annotation> annotationClass() default Annotation.class;
Class> markerInterface() default Class.class;
String sqlSessionTemplateRef() default "";
String sqlSessionFactoryRef() default "";
Class extends MapperFactoryBean> factoryBean() default MapperFactoryBean.class;
}
@SpringBootApplication
@MapperScan("cn.thisforyou.core.blog.mapper")
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
SpringApplication.run(App.class,args);
}
}
在SpringBoot中使用mybatis,那它的入口就在 @MapperScan中。@MapperScan注解,是在SpringBoot的启动类中。
@MapperScan中有个 @Import 注解。
@Import 注解,可以加载某个类,放到Spring的IOC中管理
在Spring中,要将Bean放到IOC容器中管理的话,有几种方式。@Import 此种方法
@Configuration 与 @Bean 注解结合使用
@Controller @Service @Repository @Component
@ComponentScan 扫描。
重写BeanFactoryPostProcessor 的postProcessBeanFactory()方法,也可以实现Bean的注入