0

I'am trying to get the methods that are using a custom annotation, but when i get the method, i can't get any annotation from it, every paramter that cites "annotation" is null.

My annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String value() default "";
}

Class using annotation:

public interface Interface {
    void doSomething();
}

@Repository
public class ImplementationClass implements Interface {
    
    @Override
    @MyAnnotation("some_value")
    public void doSomething() {

    }
}

Getting annotation:

@Configuration
public class MyAnnotationScanner implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        for (String beanName : applicationContext.getBeanNamesForAnnotation(Repository.class)) {
            Object bean = applicationContext.getBean(beanName);
            for (Method beanMethod : bean.getClass().getDeclaredMethods()) {
                if (beanMethod.isAnnotationPresent(MyAnnotation.class))
                    // do something
            }
        }
    }
}

I'm able to get the correct method, but when i check with intellij it has no annotations and the "isAnnotationPresent" method always returns false.

Toniotti
  • 57
  • 6

1 Answers1

0

I found a solution in using the AnnotationUtils.findAnnotation() method.

Basically for every beanMethod, you get the annotation using the findAnnotation method.

var annotation = AnnotationUtils.findAnnotation(beanMethod, MyAnnotation.class);
Matthias Steinbauer
  • 1,731
  • 11
  • 24
Toniotti
  • 57
  • 6