Search code examples
javaspringannotationsapplicationcontext

Java annotation scanning with spring


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

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?


Solution

  • 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.