1. 程式人生 > >017 包掃描器和標記註解

017 包掃描器和標記註解

context com autowire for 註意 ges conf wired out

一 .概述

在之前我們使用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 {

}

千萬需要註意的是,使用包含屬性一定要聲明不使用默認掃描行為.

017 包掃描器和標記註解