1.核心注解@ComponentScan
作用范围扫描的方式,扫描特定的注解,将其注册到Spring ioc容器中
@ComponentScan(
excludeFilters = {@Filter(
type = FilterType.CUSTOM,
classes = {TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {AutoConfigurationExcludeFilter.class}
)}
)
excludeFilters:过滤不需要扫描的类型。 @Filter 过滤注解 FilterType.CUSTOM 过滤类型为自定义规则,即指定特定的class classes :过滤指定的class,即剔除了TypeExcludeFilter.class、AutoConfigurationExcludeFilter.class
从以上源码,我们可以得出结论:
1.@SpringBootApplication的源码包含了@ComponentScan, 故,只要@SpringBootApplication注解的所在的包及其下级包,都会讲class扫描到并装入spring ioc容器
2.如果你自定义的定义一个Spring bean,不在@SpringBootApplication注解的所在的包及其下级包, 都必须手动加上@ComponentScan注解并指定那个bean所在的包。
2.核心作用:
定义一个Spring bean 一般是在类上加上注解 @Service 或@Controller 或 @Component就可以, 但是,spring怎么知道有你这个bean的存在呢? 故,我们必须告诉spring去哪里找这个bean类。 @ComponentScan就是用来告诉spring去哪里找bean类。
告诉Spring去扫描@componentscan指定包下所有的注解类,然后将扫描到的类装入spring bean容器。 例如:@ComponentScan(“com.agan.boot.scan”),就只能扫描com.agan.boot.scan包下的注解类。 如果不写?就像@SpringBootApplication的@ComponentScan没有指定路径名?它去哪里找? @SpringBootApplication注解的所在的包及其下级包,都会讲class扫描到并装入spring ioc容器
3.实践
3.1 新建一个ComponentScan测试类
package com.agan.boot.scan;
import org.springframework.stereotype.Service;
@Service
public class TestComponentScan {
}
3.2在com.example.demo下面建个启动类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(Application.class, args);
TestComponentScan componentScan = run.getBean(TestComponentScan.class);
System.out.println(componentScan.toString());
}
}