在编写 MyBatis 的 Mapper 接口时,可以在 Mapper 接口上加上@Mapper@Repository两个注解,到底用哪个呢?现在我就带你研究 😎

使用 @Mapper

使用@Mapper后,不需要在配置类上加@MapperScan注解,通过mapper.xml里面的namespace属性对应相关的mapper类,Spring 将动态的生成Bean后注入到Service中。

使用 @Repository

使用@Repository则需要在配置类上加@MapperScan注解,然后生成dao层的bean,之后被注入到Service层中。

Last But Not least

Dao明明是一个接口,怎么就能调用呢?其实我们在编译的时候会将mapper的接口实例化。至于原理还有待完善,不过这块了解原理意义不大,如果有时间还是把精力放在Spring源码上好一些。