【spring】之基於注解@ComponentScan的一些使用


基於xml形式ComponentScan的使用如下

 

<context:component-scan base-package="com.luna" use-default-filters="false">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

基於注解@ComponentScan的使用

@Configuration

/*@ComponentScan(value = "com.luna", includeFilters = {

   // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
   // @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} )
   @ComponentScan.Filter(type = FilterType.CUSTOM,value = {MyFilter.class})
 },useDefaultFilters = false)*/

@ComponentScan(value = "com.luna"

    //排除某些類
    excludeFilters = { //排除Controller注解標注的類
    @ComponentScan.Filter(type
= FilterType.ANNOTATION, classes = {Controller.class}),
//排除指定類型的類 @ComponentScan.Filter(type
= FilterType.ASSIGNABLE_TYPE,value ={com.luna.service.PersonService.class} ) }) public class ScanConfig { }

 

測試

@Test
    public void test(){
        AnnotationConfigApplicationContext applicationContext = 
                new AnnotationConfigApplicationContext(ScanConfig.class);
        String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
        Arrays.asList(beanDefinitionNames).stream().forEach(x->System.out.println("掃描到的Bean---"+x));
    }

 

 

 

@ComponentScan一些常用參數

//基本屬性 value/basePackages:指定一組要掃描的包,將掃描這些包及其子包下的文件.(默認基包為配置類所在的包)

classes:直接指定掃描的一些類,這些類所在的包及其子包也會被掃描。

nameGenerator:指定一個默認掃描組件的命名類, 默認命名使用組件類名第一個字小寫。

excludeFilters:指定掃描的時候排除某些類,按什么規則,需要一組@ComponentScan.Filter的注解配置,每個@Filter可以配置一組過濾規則,多個@Filter可以基於正則/注解/具體類配置不同的過濾規則。

includeFilters:指定掃描的時候,只包含某些類。

useDefaultFilters 自動掃描Controller Component Service Resposity 這四個注解
所以在不指定明確包的情況下如 com.luna 全包掃描,會掃描到Controller Component Service Resposity 四個注解

 

FilterType.ANNOTATION(默認) 一組注解,命中所有使用該注解的類,{MyAnno.class} -
FilterType.ASSIGNABLE_TYPE 一組具體類 -
FilterType.ASPECTJ - 一組表達式,使用Aspectj表達式命中類
FilterType.REGEX - 一組表達式,使用正則命中類
FilterType.CUSTOM 自定義的TypeFilter. -


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM