017 包扫描器和标记注解

一 .概述

在之前我们使用spring时,最常用的就是组件扫描器配合Bean标记注解整体进行Bean的注册.

  xml形式: 

<context:component-scan base-package="" />

我们配置基础包,spring会帮助我们将基础包下所有的类进行扫描,一旦发现有类被标记上了一下四个注解就会进行注册.

[1]@Controller

[2]@Service

[3]@Component

[4]Repository

现在我们使用注解模式,同样有一套可以替换上述配置的方案.


 二 .使用注解完成扫描器

[1] 创建测试Bean

@Controller
public class PersonController {

}
@Service
public class PersonService {

}
@Repository
public class PersonDAO {

}

[2] 创建配置类

@Configuration
@ComponentScan(basePackages="com.trek.springConfig.scan")
public class ScanConfig {

}

[3]创建测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes= {ScanConfig.class})
public class ScanTest {
    @Autowired
    private ApplicationContext context;
    
    @Test
    public void test() {
        String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
        
    }
}

查看运行结果:

scanConfig
personController
personDAO
personService

我们发现我们实现了包扫描器加Bean的标记注解组合进行Bean的批量注册.


 三 .包扫描器的高级功能

在之前我们使用包扫描的时候,可以指定进行扫描组件和排除指定组件.

我们将之前的配置类进行修改.

@Configuration
@ComponentScan(basePackages = "com.trek.springConfig.scan", excludeFilters = {
        @Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) })
public class ScanConfig {

}

我们使用排除属性进行排除.

然后运行测试类:

scanConfig
personDAO
personService

我们可以发现@Controller被排除掉了.

我们使用指定注解进行扫描:

@Configuration
@ComponentScan(basePackages = "com.trek.springConfig.scan", includeFilters = {
        @Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) },useDefaultFilters=false)
public class ScanConfig {

}

千万需要注意的是,使用包含属性一定要声明不使用默认扫描行为.

原文地址:https://www.cnblogs.com/trekxu/p/9094864.html