使用 spring 进行 Java 注释扫描 [英] Java annotation scanning with spring

查看:53
本文介绍了使用 spring 进行 Java 注释扫描的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要用名称注释的类很少,所以我将注释定义为

I have few classes that I need to annotate with a name so I defined my annotation as

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

现在需要这个注解的类定义为

Now the class that needs this annotation is defined as

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

我用下面的代码扫描注释

I used below code to scan the annotations

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" ->MyClassInfo] 的对象,但我需要映射包含 "myClass" 作为键,这是注释的值而不是 bean 名称.

The problem is that the map returned contains ["myClassInfo" -> object of MyClassInfo] but I need the map to contain "myClass" as key, which is the value of the Annotation not the bean name.

有没有办法做到这一点?

Is there a way of doing this?

推荐答案

只要拿到注解对象,取出值

Just get the annotation object and pull out the value

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;

如果不清楚,请告诉我.

Let me know if that's not clear.

这篇关于使用 spring 进行 Java 注释扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆