【Spring源码解析】组件注册-@ComponentScan注册bean
    
  
      
      
     
    
      
         前言
接上一篇 Spring源码解析之注解注册bean
 实现
- 按照平时的开发, 我们创建几个类
 
1 2 3
   | @Controller public class BookController { }
   | 
 
1 2 3
   | @Service public class BookService { }
   | 
 
1 2 3
   | @Repository public class BookDao { }
   | 
 
- 配置
 
1 2 3 4 5 6 7 8 9
   | @Configuration @ComponentScan(value = "cn.idea360") public class BeanConfig {
      @Bean     public Person person() {         return new Person("config", 18);     } }
   | 
 
- 引入单元测试
 
1 2 3 4 5 6
   | <dependency>     <groupId>org.junit.jupiter</groupId>     <artifactId>junit-jupiter</artifactId>     <version>RELEASE</version>     <scope>test</scope> </dependency>
   | 
 
- 测试
 
1 2 3 4 5 6 7 8 9 10 11
   | class IocTest {
      @Test     public void test01() {         AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);         String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();         for (String name: beanDefinitionNames) {             System.out.println(name);         }     } }
  | 
 
输出结果
1 2 3 4 5 6 7 8 9
   | org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory beanConfig bookController bookDao bookService person
   | 
 
可以看出我们添加了注解并在指定包下的bean全部被注册进了容器
- 如果我们想按注解排除一部分
 
1 2 3 4 5 6 7 8 9 10 11
   | @Configuration @ComponentScan(value = "cn.idea360", excludeFilters = {         @ComponentScan.Filter(type = FilterType.ANNOTATION, value = {Controller.class}) }) public class BeanConfig {
      @Bean     public Person person() {         return new Person("config", 18);     } }
   | 
 
 最后
本篇到此结束,欢迎大家关注公众号【当我遇上你】。