2018年8月27日 星期一

@ComponentScan 排除或包括 @Component (Spring 3.x 二十六)


AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(Apple.class);
for (String s : app.getBeanDefinitionNames()) {
    System.out.println(s);
}
app.close();

※Apple.class 不管有沒有加 annotation 一定會有



※Apple.class

// @ComponentScan(excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Component.class) })
// @ComponentScan(useDefaultFilters = false, includeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Component.class) })
    
// @ComponentScan(excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Repository.class) })
// @ComponentScan(useDefaultFilters = false, includeFilters = { @Filter(type = FilterType.ANNOTATION, classes = Controller.class) })
// @ComponentScan(useDefaultFilters = false, includeFilters = { @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = Chicken.class) })
@ComponentScan(useDefaultFilters = false, includeFilters = { @Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class) })
// @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = MyTypeFilter.class) })

※如果使用 includeFilters 時,一定要將 useDefaultFilters 設為 false,否則無效,表示只包括什麼

※第一個和第二個是有問題的,使用 excludeFilters 和 Component,結果是什麼都沒有;
使用 includeFilters 和 Component,結果是什麼都有



public class MyTypeFilter implements TypeFilter {
    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory)
            throws IOException {
        // System.out.println(metadataReader.getAnnotationMetadata().getAnnotationTypes());
        // System.out.println(metadataReader.getClassMetadata().getClassName());//
        // package.class
        // System.out.println(metadataReader.getResource().getFilename());// name.class
        // System.out.println(metadataReaderFactory.getMetadataReader(metadataReader.getResource()).getAnnotationMetadata().getSuperClassName());
    
        Set<String> set = metadataReader.getAnnotationMetadata().getAnnotationTypes();
        if (new ArrayList<String>(set).contains("org.springframework.stereotype.Component")) {
            return false;
        }
        return true;
    }
}

※使用這個 class,配合上面的 FilterType.CUSTOM,可以排除或包括 @Component

沒有留言:

張貼留言