Spring注解驱动 @ComponentScan组件扫描

1. @ComponentScan流程

1.1. 编写Bean

1
2
3
4
5
package demo.spring.bean;
import org.springframework.stereotype.Component;
@Component
public class Car {
}
1
2
3
4
5
package demo.spring.bean;
import org.springframework.stereotype.Component;
@Component
public class Person {
}

1.2. 组件扫描

1
2
3
4
@Configuration
@ComponentScan("demo.spring") // 要扫描的包及其子包
public class BeanConfig {
}

1.3. 测试方法

1
2
3
4
5
6
7
@Test
public void test() {
ApplicationContext ioc = new AnnotationConfigApplicationContext(BeanConfig.class);
// 输出容器中所有的组件名称
String[] names = ioc.getBeanDefinitionNames();
Arrays.stream(names).forEach(System.out::println);
}

2. 扫描多个包

方式1:使用多个@ComponentScan注解

重复注解是Java8的新特性

1
2
3
4
5
@Configuration
@ComponentScan("demo.spring.service")
@ComponentScan("demo.spring.dao")
public class BeanConfig {
}

方式2:使用@ComponentScans

1
2
3
4
5
6
@Configuration
@ComponentScans({
@ComponentScan("demo.spring.service"),
@ComponentScan("demo.spring.dao") })
public class BeanConfig {
}

3. @ComponentScan的属性

3.1. excludeFilters排除扫描

1
2
3
4
5
6
@Configuration
@ComponentScan(value = "demo.spring", excludeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = { Controller.class, Service.class }),
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { Person.class, Car.class }) })
public class BeanConfig {
}

3.2. includeFilters包含扫描

1
2
3
4
5
6
7
@Configuration
// useDefaultFilters=false禁用@ComponentScan的默认规则(默认规则就是扫描所有)
@ComponentScan(value = "demo.spring", useDefaultFilters = false, includeFilters = {
@Filter(type = FilterType.ANNOTATION, classes = { Controller.class, Service.class }),
@Filter(type = FilterType.ASSIGNABLE_TYPE, classes = { Person.class, Car.class }) })
public class BeanConfig {
}
panchaoxin wechat
关注我的公众号
支持一下