- @ComponentScan是组件扫描注解,用来扫描@Controller @Service @Repository这类
- @MapperScan 是扫描mapper类的注解,在需要扫描的mapper类上加@Mapper
注:@Repository为spring包下的,@MapperScan为ibatis包下的,如果使用mybatis,建议使用@Mapper
首先,@ComponentScan是组件扫描注解,用来扫描@Controller @Service @Repository这类,主要就是定义扫描的路径从中找出标志了需要装配的类到Spring容器中
其次,@MapperScan 是扫描mapper类的注解,就不用在每个mapper类上加@MapperScan了
这两个注解是可以同时使用的。
@Mapper 注解针对的是一个一个的类,相当于是一个一个 Mapper.xml 文件。而一个接口一个接口的使用 @Mapper,太麻烦了,于是 @MapperScan 就应用而生了。@MapperScan 配置一个或多个包路径,自动的扫描这些包路径下的类,自动的为它们生成代理类。
方式一:使用@Mapper注解
直接在Mapper类上面添加注解@Mapper,这种方式要求每一个mapper类都需要添加此注解,麻烦。
@Mapper
public interface DemoMapper {
@Insert("insert into Demo(name) values(#{name})")
@Options(keyProperty="id",keyColumn="id",useGeneratedKeys=true)
public void save(Demo demo);
}
方式二:使用@MapperScan注解
通过使用@MapperScan可以指定要扫描的Mapper类的包的路径
@SpringBootApplication
@MapperScan("com.kfit.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
或者:
@SpringBootApplication
@MapperScan("com.kfit.*.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
使用@MapperScan注解多个包
@SpringBootApplication
@MapperScan({"com.kfit.demo","com.kfit.user"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
如果mapper类没有在Spring Boot主程序可以扫描的包或者子包下面,可以使用如下方式进行配置:
@SpringBootApplication
@MapperScan({"com.kfit.*.mapper","org.kfit.*.mapper"})
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}