使用Spring进行Java注释扫描 [英] Java annotation scanning with spring
本文介绍了使用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" -> object of MyClassInfo]
,但是我需要映射包含"myClass"
作为键,这是Annotation的值而不是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;
让我知道是否不清楚.
这篇关于使用Spring进行Java注释扫描的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文