1. 程式人生 > 其它 >Spring - @ComponentScan包掃描機制

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 -
夢想是鹹魚
關注一下吧
以上為本篇文章的主要內容,希望大家多提意見,如果喜歡記得點個推薦哦 作者:夢想是鹹魚 出處:https://www.cnblogs.com/maggieq8324/ 本文版權歸作者和部落格園共有,歡迎轉載,轉載時保留原作者和文章地址即可。