Spring - @CompentScan全解

2021-08-17 17:00:54 浏览数 (1)


基本使用

在配置类上写@CompentScan注解来进行包扫描

代码语言:javascript复制
@Configuration
@ComponentScan(basePackages = {"com.artisan"})
public class MainConfig {

}

excludeFilters

代码语言:javascript复制
@Configuration
@ComponentScan(basePackages = {"com.artisan"},excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
        @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {ArtisanService.class})
})
public class MainConfig {
}

这里会 排除标注了@Controller注解 和 特定的ArtisanService ,不会被加载到IOC容器中。


includeFilters

若使用包含的用法, 需要把useDefaultFilters属性设置为false(true表示扫描全部的)

代码语言:javascript复制
@Configuration
@ComponentScan(basePackages = {"com.artisan"},includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class, Service.class})
},useDefaultFilters = false)
public class MainConfig {
}


@ComponentScan.Filter

4种类型


自定义FilterType

代码语言:javascript复制
import org.springframework.core.io.Resource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.ClassMetadata;
import org.springframework.core.type.classreading.MetadataReader;
import org.springframework.core.type.classreading.MetadataReaderFactory;
import org.springframework.core.type.filter.TypeFilter;

import java.io.IOException;

 
public class ArtisanFilterType implements TypeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        //获取当前类的注解源信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

        //获取当前类的class的源信息
        ClassMetadata classMetadata = metadataReader.getClassMetadata();
        //获取当前类的资源信息
        Resource resource =  metadataReader.getResource();
        System.out.println("类的路径:" classMetadata.getClassName());
        if(classMetadata.getClassName().contains("dao")) {
            return true;
        }
        return false;
    }
}

引用自定义类型的Filter

代码语言:javascript复制
@ComponentScan(basePackages = {"com.tuling.testcompentscan"},excludeFilters = { 
        @ComponentScan.Filter(type = FilterType.CUSTOM,value = ArtisanFilterType.class)
},includeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION,value = Repository.class)
})

测试的话,打印下beanDefinition 即可

代码语言:javascript复制
public class MainClass {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(MainConfig.class);
        String[] beanDefinationNames = ctx.getBeanDefinitionNames();
        for (String name:beanDefinationNames) {
            System.out.println("bean的定义信息:" name);
        }

    }
}

0 人点赞