2014-11-13 55 views
0

在執行基於註釋的組件掃描時,是否有一種方法可以在春季應用限定符?Spring註釋和基於限定符的掃描

我有幾個類用我的自定義註釋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被掃描?

回答

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; 
    } 

} 
+0

謝謝您的回答,我會試試看;我認爲這是我正在尋找的。我還想動態地在註解上設置限定符值,但我認爲它更像是一個標準的java註釋問題,而不是一個特定於Spring的註釋問題。 – Kesh

+0

很酷,但你確定你不想使用[Spring profile](http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-definition-profiles -java)支持? –

+0

我之前沒有真正使用過配置文件,但該選項看起來更好。如果我使用它,我可能不需要實現一個自定義的'TypeFilter'。我是否正確地說它不需要伴隨其他註釋,如配置或組件;除非任何指定的配置文件處於活動狀態,否則組件掃描器不會掃描課程? – Kesh