前言
@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訪問異常
