Find method level custom annotation in a Spring context

前端 未结 3 1652
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 14:03

All I wanted to find out was \"all the class/methods in Spring beans which are annotated as @Versioned\".

I created my custom annotation as,

@Target({Ele         


        
3条回答
  •  一个人的身影
    2021-02-05 14:14

    applicationContext.getBean(beanName).getClass() gives you the proxied class that Spring creates around your target class.

    What you want is to get hold of the target class, if any, from your Spring bean.

    Spring provides a nice utility class for resolving this called AopUtils.class.

    Below is how you would use it:

    for(String beanName: applicationContext.getBeanDefinitionNames()){
        Method[] methods = AopUtils.getTargetClass(applicationContext.getBean(beanName)).getDeclaredMethods();
    
        for(Method m: methods){
            if(m.isAnnotationPresent(Versioned.class){
            }
        }
    }
    

    Note that you will have to import the spring-aop Maven dependency to get hold of the AopUtils class:

    
        org.springframework
        spring-aop
        ${spring.version}
    
    

提交回复
热议问题