![](/img/trans.png)
[英]Spring boot component scan does not recognize qualifier annotation for different beans
[英]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.