什么时候用@ComponentScan?与@MapperScan有什么区别?
@ComponentScan与@MapperScan有什么区别?
什么时候用@ComponentScan?
@ComponentScan是SpringBoot的注解,如其意“Sacn”是扫描的意思。
SpringBoot在没配置@ComponentScan的情况下,默认只扫描和主类处于同包下的Class
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//@ComponentScan(basePackages = "com.自定义.mall")如果不加,只扫描和主类处于同包下的Class!!!
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
例如下述情况:
不加@ComponentScan可用的范围
必须要加的情况
SpringBoot的启动类GunRestApplication 在restfulapi包下,但是存在一个与restfulapi包同级的modular包也想被扫描到就必须要使用。
@ComponentScan与@MapperScan有什么区别?
首先要搞清楚它们两个分别是干什么的
(1)显然两者都有Scan——“扫描”,@MapperScan和@ComponentScan都是扫描包
(2)@ComponentScan是组件扫描注解,用来扫描@Controller @Service @Repository这类,主要就是定义扫描的路径从中找出标志了需要装配的类到Spring容器中
(3)@MapperScan 是扫描mapper类的注解,就不用在每个dao层的各个类上加@Mapper了
举一个例子:
如下是我的SpringBoot项目,里面使用了MyBatisPlus,用了@MapperScan
dao包下的BookDao
//@Mapper
@Repository
public interface BookDao extends BaseMapper<Book> {
}
使用@MapperScan有两种方式
可以在启动类上标注
@SpringBootApplication
@MapperScan("com.harmony.dao")
public class SSMPApplication {
public static void main(String[] args) {
// 启动springboot时,断开读取外部临时配置对应的入口,也就是去掉读取外部参数的形参
// SpringApplication.run(SSMPApplication.class);
SpringApplication.run(SSMPApplication.class, args);
}
}
或者在配置类MPConfig类使用
@Configuration
@MapperScan("com.harmony.dao") // 使用该注解,在dao层的各个类中就不用添加 @Mapper
public class MPConfig {
// 第三方bean的配置方式
@Bean
// 想使用MybatisPlus提供的分页,必须使用MP的拦截器
public MybatisPlusInterceptor mybatisPlusInterceptor() {
// 定义Mp拦截器的壳
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加具体的拦截器 PaginationInnerInterceptor -> 分页
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
上述两种效果是一样的!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)