简体   繁体   中英

Spring method annotations null

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.

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

I was using isAnnotationPresent method but it was always returning false. I have then used AnnotationUtils.findAnnotation(method, <Annotation.class>)

Here is how I am finding method that is using custom annotation:

for (String beanName : applicationContext.getBeanDefinitionNames()) {
        Object bean = applicationContext.getBean(beanName);
        Class<?> objClass = bean.getClass();
        for (Method m : objClass.getDeclaredMethods()) {

            Annotation a = AnnotationUtils.findAnnotation(m, <Annotation_NAME>.class);
            if (a != null) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM