Spring - @ComponentScan包掃描機制


前言

@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 -
夢想是咸魚
關注一下吧


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM