在spring boot中,自定义方法注解,在有其他注解存在的情况下,可能出现无法获取自定义注解的情况
利用ApplicationContext扫描时,通过debug得到class文件名含有EnhancerBySpringCGLIB,类似于这样:
或含有$ProxyXXX,类似于这样:
其根本原因在于,applicationContext.getBeansWithAnnotation(类注解.class) 方法获取到的Bean,是GClib代理后的类或者Jdk代理的类,导致 bean.getClass().getDeclaredMethods() 拿不到原真实类的方法
需要根据情况,利用反射去获取对应真实类,拿到其方法
2 解决方案这里封装了两个注解,用于监听MQ消息:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MqttClient {
String value() default "";
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface MqttListener {
String[] value() default {};
int qos() default 0;
}
其中,@MqttClient 类注解,@MqttListener 方法注解
新增一个配置类实现CommandLineRunner,实现其run方法,扫描对应注解的bean
@Component
@Slf4j
public class MqttAnnotationScanner implements CommandLineRunner {
@Autowired
private ApplicationContext applicationContext;
@Override
public void run(String... args) throws Exception {
Map beansMap = applicationContext.getBeansWithAnnotation(MqttClient.class);
for (Object bean : beansMap.values()) {
Method[] declaredMethods = null;
//判断是否为JdkDynamicProxy代理类
if (AopUtils.isJdkDynamicProxy(bean)){
Object singletonTarget = AopProxyUtils.getSingletonTarget(bean);
if (singletonTarget != null) {
declaredMethods = singletonTarget.getClass().getDeclaredMethods();
}
} else if (AopUtils.isCglibProxy(bean)) {//判断是否为CglibProxy代理类
declaredMethods = bean.getClass().getSuperclass().getDeclaredMethods();
} else {
declaredMethods = bean.getClass().getDeclaredMethods();
}
if (declaredMethods != null) {
for (Method method : declaredMethods) {
MqttListener annotation = method.getAnnotation(MqttListener.class);
if (annotation != null) {
// ......执行相应的逻辑
}
}
}
}
}
}
这样,就可以拿到对应的CGlib代理类的注解方法了,实现与其他注解共存
@RedisLock(lockKey = "{{#entity.uid}}")
@MqttListener(Topic.TEST)
public void test(MqttEntity entity) {
log.info("接收到的数据:{}", entity);
testSync(entity.getValues());
}



