2012-05-11 113 views
1

我有我需要用一個名字來註釋,所以我定義我的註釋爲的Java註釋掃描帶彈簧

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.TYPE) 
public @interface JsonUnmarshallable { 
    public String value(); 
} 

現在需要這個註釋的類定義爲

@JsonUnmarshallable("myClass") 
public class MyClassInfo { 
<few properties> 
} 

幾類我用下面的代碼來掃描註釋

private <T> Map<String, T> scanForAnnotation(Class<JsonUnmarshallable> annotationType) { 
    GenericApplicationContext applicationContext = new GenericApplicationContext(); 
    ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(applicationContext, false); 
    scanner.addIncludeFilter(new AnnotationTypeFilter(annotationType)); 
    scanner.scan("my"); 
    applicationContext.refresh(); 
    return (Map<String, T>) applicationContext.getBeansWithAnnotation(annotationType); 
} 

問題是返回的map包含["myClassInfo" -> object of MyClassInfo]但我需要該映射包含"myClass"作爲鍵,這是Annotation的值而不是bean的名稱。

有沒有辦法做到這一點?

回答

3

剛剛得到註釋對象,並拉出值

Map<String,T> tmpMap = new HashMap<String,T>(); 
JsonUnmarshallable ann; 
for (T o : applicationContext.getBeansWithAnnotation(annotationType).values()) { 
    ann = o.getClass().getAnnotation(JsonUnmarshallable.class); 
    tmpMap.put(ann.value(),o); 
} 
return o; 

讓我知道這是不明確的。

0

也許你可以使用http://scannotation.sourceforge.net/框架來實現。

希望它有幫助。

+0

我試圖使用框架,它是更靈活,但是我無法找到特定於我的使用情況。你能告訴我怎樣才能得到annotationDb返回一個由類 – Manoj

+0

中定義的註解的值作爲鍵值的Map對不起,我錯了,但你可以發佈過程那個Map –

0

您可以向ClassPathBeanDefinitionScanner提供一個自定義BeanNameGenerator,它可以查找註釋的值並將其作爲bean名稱返回。

我認爲沿着這些方向的實施應該適合你。

package org.bk.lmt.services; 

import java.util.Map; 
import java.util.Set; 

import org.springframework.context.annotation.AnnotationBeanNameGenerator; 
public class CustomBeanNameGenerator extends AnnotationBeanNameGenerator{ 
    @Override 
    protected boolean isStereotypeWithNameValue(String annotationType, 
      Set<String> metaAnnotationTypes, Map<String, Object> attributes) { 

     return annotationType.equals("services.JsonUnmarshallable"); 
    } 
} 

添加到您以前的掃描儀代碼: scanner.setBeanNameGenerator(new CustomBeanNameGenerator());

1

在我來說,我寫了象下面這樣:

ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false); 
scanner.addIncludeFilter(new AnnotationTypeFilter(JsonUnmarshallable.class)); 
Set<BeanDefinition> definitions = scanner.findCandidateComponents("base.package.for.scanning"); 

for(BeanDefinition d : definitions) { 
    String className = d.getBeanClassName(); 
    String packageName = className.substring(0,className.lastIndexOf('.')); 
    System.out.println("packageName:" + packageName + " , className:" + className); 
}