簡體   English   中英

基於Spring注釋和限定符的掃描

[英]Spring Annotation and Qualifier Based Scan

春天,有沒有辦法在執行基於注釋的組件掃描時應用限定符?

我有幾個用自定義注釋MyAnnotation注釋的類。

@MyAnnotation
public class ClassOne {
}

@MyAnnotation
public class ClassTwo {
}

@Configuration
@ComponentScan(basePackages = { "common" }, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class) })
public class ClassProvider {
}

我想做的是,使用此批注掃描類的子集,根據某些條件(例如來自用戶的某些輸入)有選擇地進行掃描。

是否可以說指定一個限定詞和注釋,還可以使用組件掃描過濾器指定它,像這樣-

@MyAnnotation (qualifier = "one")
public class ClassOne {
}

@MyAnnotation (qualifier = "two")
public class ClassTwo {
}

@Configuration
@ComponentScan(basePackages = { "common" }, useDefaultFilters = false, includeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = MyAnnotation.class, qualifier = "one") })
public class ClassProvider {
}

這樣只有ClassOne會被掃描?

您可以實現自定義TypeFilter,以便您的@ComponentScan看起來像:

@ComponentScan(includeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM, value = MyAnnotation.class) })

和TypeFilter實現:

public class TypeOneFilter implements TypeFilter {

    @Override
    public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException {
        final AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();

        if (annotationMetadata.hasAnnotation(MyAnnotation.class.getName())) {
            final Map<String, Object> attributes = annotationMetadata.getAnnotationAttributes(MyAnnotation.class.getName());

            return "one".equals(attributes.get("qualifier"));
        }

        return false;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM