详解 @MapperScan 注解和 @Mapper 注解

mac2024-03-13  37

 

@Mapper 这个注解的定义如下:

@Documented @Inherited @Retention(RUNTIME) @Target({ TYPE, METHOD, FIELD, PARAMETER }) public @interface Mapper { // Interface Mapper }

@Mapper 一般我们用在接口上,代码如下:

@Mapper public interface UserDAO { @Select("select * from user where name = #{name}") User find(String name); @Select("select * from user where name = #{name} and pwd = #{pwd}") /** * 对于多个参数来说,每个参数之前都要加上@Param注解, * 要不然会找不到对应的参数进而报错 */ User login(@Param("name")String name, @Param("pwd")String pwd); }

使用 @Mapper,最终 Mybatis 会有一个拦截器,会自动的把 @Mapper 注解的接口生成动态代理类。这点可以在 MapperRegistry 类中的源代码中查看。

@Mapper 注解针对的是一个一个的类,相当于是一个一个 Mapper.xml 文件。而一个接口一个接口的使用 @Mapper,太麻烦了,于是 @MapperScan 就应用而生了。@MapperScan 配置一个或多个包路径,自动的扫描这些包路径下的类,自动的为它们生成代理类。

@SpringBootApplication @MapperScan({"com.xttblog.mapper","com.xttblog.dao"}) public class XttblogApp { public static void main(String[] args) { SpringApplication.run(XttblogApp.class, args); } }

当使用了 @MapperScan 注解,将会生成 MapperFactoryBean, 如果没有标注 @MapperScan 也就是没有 MapperFactoryBean 的实例,就走 @Import 里面的配置,具体可以在 AutoConfiguredMapperScannerRegistrar 和 MybatisAutoConfiguration 类中查看源代码进行分析。

由此可见,动态代理和 AOP 知识非常的重要,各种框架都在大量的使用。

最新回复(0)