spring aop获取代理目标对象

2020-04-08  本文已影响0人  草_帽

spring aop获取代理目标对象

转载: https://coget.cn/archives/spring%20aop%E8%8E%B7%E5%8F%96%E4%BB%A3%E7%90%86%E7%9B%AE%E6%A0%87%E5%AF%B9%E8%B1%A1

大家一定在开发中遇见了这个问题,getClass() 后获取不到目标对象,或者说,拿到 class 后 getAnnotation() 获取不到,这些是 spring aop 将对象,改装成了代理对象。

上代码,如:扫描MQ注解

正常:

xxx.getClass().getAnnotation(MQConsumer.class);

增加 @Transactional,后 spring 事务管理器,将 Method 增改,包装了一个代理对象。

 consumers.entrySet().forEach(entry -> {
    MQConsumer consumer;
    if (AopUtils.isAopProxy(entry.getValue())) {
        consumer = AopProxyUtils.getSingletonTarget(entry.getValue()).getClass().getAnnotation(MQConsumer.class);
    } else {
        consumer = entry.getValue().getClass().getAnnotation(MQConsumer.class);
    }
});

ps:

上一篇下一篇

猜你喜欢

热点阅读