Annotationutils. findAnnotation Returns Null

I'm attempting to find all beans with a custom annotation so I can look at the annotation properties on each bean for help in a scheduled job.

Custom Spring Annotation:

@Component
@Scope("prototype")
public @interface Importer {
    String value() default "";
    String fileRegex() default "";
}

Example Class Definition (MyAwesomeImporterFramework is a base class--no annotations)

@Importer(value="spring.bean.name", fileRegex="myfile.*\\.csv")
public class MyAwesomeImporter extends MyAwesomeImporterFramework

Code to find Spring beans with annotations:

public static List<Class<?>> findBeanClasses(String packageName, Class<? extends Annotation> annotation) throws ClassNotFoundException {
    List<Class<?>> classes = new LinkedList<Class<?>>();

    ClassPathScanningCandidateComponentProvider scanner =
            new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(annotation));

    for(BeanDefinition def : scanner.findCandidateComponents(packageName)) {
        classes.add(Class.forName(def.getBeanClassName()));
    }

    return classes;
}

Code that utilizes the finder to get the annotation properties.

for(Class<?> clazz : AnnotationFinder.findBeanClasses(CLASS_BASE_PACKAGE, Importer.class)) {
    // Doesn't work either:
    // Importer annotation = clazz.getAnnotation(Importer.class);
    Importer annotation = AnnotationUtils.findAnnotation(clazz, Importer.class);
    importClasses.put(annotation.fileRegex(), annotation.value());
}

Here, both clazz.getAnnotation(Importer.class) and AnnotationUtils.findAnnotation(clazz, Importer.class) return null. Inspecting the code in the debugger shows the correct classes being identified, but annotations map on clazz is empty.

What am I missing? Both of those methods should return something, but it almost seems like the annotation has disappeared off the class during runtime??

1
James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article