使用spring进行Java注释扫描

时间:2012-05-11 10:13:22

标签: java spring annotations applicationcontext

我需要使用名称注释几个类,所以我将注释定义为

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

问题是返回的地图包含["myClassInfo" -> object of MyClassInfo]但是我需要地图包含"myClass"作为键,这是Annotation的值而不是bean名称。

有没有办法做到这一点?

4 个答案:

答案 0 :(得分:5)

只需获取注释对象并提取值

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;

如果不清楚,请告诉我。

答案 1 :(得分:2)

就我而言,我写的如下:

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

答案 2 :(得分:0)

也许您可以使用http://scannotation.sourceforge.net/框架来实现这一目标。

希望它有所帮助。

答案 3 :(得分: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());