什么时候用@ComponentScan?与@MapperScan有什么区别?

什么时候用@ComponentScan?

@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什么时候可以不加

@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;
    }
}

上述两种效果是一样的!!!

猜你喜欢

转载自blog.csdn.net/weixin_43715214/article/details/125197457