2012-05-11 111 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); 
}