在 Spring 上下文中查找方法级自定义注释
2022-09-04 00:54:32
我想找出的只是“Spring beans中所有注释为@Versioned的类/方法”。
我创建了我的自定义注释,如下所示:
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Versioned {
.....
}
当我使用Java反射来查找方法时,这个注释可以完美地工作:
for(Method m: obj.getClass().getMethods()){
if(m.isAnnotationPresent(Versioned.class)){
.... // Do something
}
但是当我访问Spring bean并尝试类似的检查时,它不起作用:
public class VersionScanner implements ApplicationContextAware{
public void setApplicationContext(ApplicationContext applicationContext){
for(String beanName: applicationContext.getBeanDefinitionNames()){
for(Method m: applicationContext.getBean(beanName).getClass().getDeclaredMethods()){
if(m.isAnnotationPresent(Versioned.class){
// This is not WORKING as expected for any beans with method annotated
}
}
}
}
}
实际上,此代码确实可以找到其他注释,例如@RequestMapping。我不确定我的自定义注释做错了什么。