使用spring进行Java注释扫描

Man*_*noj 1 java spring annotations applicationcontext

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface JsonUnmarshallable {
    public String value();
}
Run Code Online (Sandbox Code Playgroud)

现在需要此注释的类被定义为

@JsonUnmarshallable("myClass")
public class MyClassInfo {
<few properties>
}
Run Code Online (Sandbox Code Playgroud)

我使用下面的代码来扫描注释

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);
}
Run Code Online (Sandbox Code Playgroud)

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

有办法做到这一点吗?

Mad*_*ker 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;
Run Code Online (Sandbox Code Playgroud)

如果不清楚,请告诉我.


小智 5

在我的情况下,我写如下:

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);
}
Run Code Online (Sandbox Code Playgroud)