基于Spring注释和基于限定符的扫描

时间:2014-11-13 18:11:27

标签: java spring annotations

春天有没有办法在执行基于注释的组件扫描时应用限定符?

我有几个用自定义注释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

1 个答案:

答案 0 :(得分:0)

您可以实现自定义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;
    }

}