获取Bean方法注解遇异常:注解列表返回空的技术求助
解决Spring Bean方法注解获取为空的问题
嘿,我一眼就看出问题所在了——你直接通过entry.getValue().getClass()拿到的是Spring生成的代理类,而不是你自己写的原始Controller类!Spring会给标注了@RestController的Bean生成动态代理(比如CGLIB或JDK代理),代理类的方法并不会保留原始方法上的注解(除非注解特意标记了@Inherited,但即使这样也不一定能完美生效),所以你遍历代理类的方法自然拿不到想要的注解。
给你两个关键的解决思路,直接改代码就行:
1. 获取原始Bean的Class对象
用Spring提供的AopUtils.getTargetClass()方法,跳过代理类直接拿到你写的原始Controller类,这样就能正确获取到原始方法上的注解了。
修改后的完整代码示例:
import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.web.bind.annotation.RestController; import javax.annotation.PostConstruct; import java.lang.reflect.Method; import java.util.Map; @PostConstruct public void findSensitiveAnnotations(){ Map<String,Object> beans = applicationContext.getBeansWithAnnotation(RestController.class); for (Map.Entry<String, Object> entry : beans.entrySet()){ // 拿到原始Bean的Class,跳过代理类 Class<?> targetClass = AopUtils.getTargetClass(entry.getValue()); // 遍历原始类的所有声明方法 for (Method method : targetClass.getDeclaredMethods()){ System.out.println("当前方法:" + method); // 替换成你要获取的注解类型 YourSensitiveAnnotation annotation = method.getAnnotation(YourSensitiveAnnotation.class); if (annotation != null) { // 这里处理你的注解逻辑 System.out.println("找到目标注解:" + annotation); } } } }
2. 额外注意事项
- 确保你的自定义注解添加了
@Retention(RetentionPolicy.RUNTIME),否则运行时反射根本拿不到这个注解:import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Retention(RetentionPolicy.RUNTIME) public @interface YourSensitiveAnnotation { // 注解属性 } - 如果需要获取父类继承来的方法注解,把
getDeclaredMethods()换成getMethods(),记得过滤掉Object类自带的方法(比如toString、hashCode这些)。 - 如果你用的是Spring Boot,
spring-boot-starter-web已经包含了AOP相关依赖,不用额外引入;如果是普通Spring项目,要确保引入了Spring AOP的依赖。
内容的提问来源于stack exchange,提问作者OrangePot
相关产品推荐
相关产品推荐

