Spring

前言

@ComponentScan注解默认装配标识了@Controller,@Service,@Repository,@Component注解的Bean到IOC容器中,这里我们看一下它的扫描机制。


默认扫描机制

  • 程序结构如图,TestController属于启动类子级

在这里插入图片描述

  • 访问正常

在这里插入图片描述

  • 程序结构如图,TestController属于启动类同级

在这里插入图片描述

  • 访问正常

在这里插入图片描述

  • 程序结构如图,TestController属于启动类上级

在这里插入图片描述

  • 访问异常

在这里插入图片描述

  • 结论:默认情况下,@ComponentScan扫描入口类同级及其子级包下的所有文件。

@ComponentScan的使用

  • @ComponentScan 的作用就是根据定义的扫描路径,把符合扫描规则的类装配到spring容器中。

@ComponentScan常用参数

参数 作用
basePackages与value 用于指定包的路径,进行扫描
basePackageClasses 用于指定某个类的包的路径进行扫描
nameGenerator bean的名称的生成器
useDefaultFilters 是否开启对@Component,@Repository,@Service,@Controller的类进行检测
includeFilters 包含的过滤条件 FilterType.ANNOTATION:按照注解过滤 FilterType.ASSIGNABLE_TYPE:按照给定的类型 FilterType.ASPECTJ:使用ASPECTJ表达式 FilterType.REGEX:正则 FilterType.CUSTOM:自定义规则
excludeFilters 排除的过滤条件,用法和includeFilters一样

@ComponentScan指定扫描

  • 程序结构如图,TestController属于启动类上级

在这里插入图片描述

  • 指定扫描路径
@SpringBootApplication
@ComponentScan("com.coisini")
public class SpringLearnApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringLearnApplication.class, args);
    }
}
  • 访问正常

在这里插入图片描述


excludeFilters 排除扫描

  • 新建测试TestOneController
@RestController
@RequestMapping("/testOne")
public class TestOneController {

    @Autowired
    private TestInter testInter;

    @GetMapping(value = "/test")
    public String test(){
        return testInter.sayHello();
    }

}
  • 忽略扫描TestOneController
@SpringBootApplication
@ComponentScan(value = "com.coisini",
                excludeFilters = {@ComponentScan.Filter(
                        type = FilterType.ASSIGNABLE_TYPE,
                        classes = TestOneController.class)})
public class SpringLearnApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringLearnApplication.class, args);
    }

}
  • TestController访问正常

在这里插入图片描述

  • TestOneController访问异常

在这里插入图片描述

- End -
梦想是咸鱼
关注一下吧
以上为本篇文章的主要内容,希望大家多提意见,如果喜欢记得点个推荐哦
作者:Maggieq8324
本文版权归作者和博客园共有,欢迎转载,转载时保留原作者和文章地址即可。
原文地址:https://www.cnblogs.com/maggieq8324/p/15118214.html