日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

cglib动态代理导致注解丢失问题及如何修改注解允许被继承

發布時間:2025/3/8 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 cglib动态代理导致注解丢失问题及如何修改注解允许被继承 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

現象

  SOAService這個bean先后經過兩個BeanPostProcessor,會發現代理之后注解就丟失了。

  

    

開啟了cglib代理

@SpringBootApplication @EnableAspectJAutoProxy(proxyTargetClass = true) public class Application {public static void main(String[] args) {SpringApplication app = new SpringApplication(Application.class);app.run(args);} }

為什么開啟這個代理模式呢

  http://www.cnblogs.com/hujunzheng/p/8428422.html 

如何解決這個問題

  在自定義注解上添加@Inherited。如果是第三方的注解,調整項目接口層或者拿到這個注解通過代碼方式加上@Inherited注解, 或者如下圖所示。

  

?

public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {Service anon = bean.getClass().getAnnotation(Service.class);if (anon != null) {try {InvocationHandler h = Proxy.getInvocationHandler(anon);//設置@Service注解支持繼承,應對動態代理導致類上的@Service注解丟失Field typeField = h.getClass().getDeclaredField("type");typeField.setAccessible(true);Field annotationTypeField = Class.class.getDeclaredField("annotationType");annotationTypeField.setAccessible(true);AnnotationType annotationType = (AnnotationType) annotationTypeField.get(typeField.get(h));Field inheritedField = AnnotationType.class.getDeclaredField("inherited");this.updateFinalModifiers(inheritedField);inheritedField.set(annotationType, true);// 獲取 AnnotationInvocationHandler 的 memberValues 字段Field memberValuesField = h.getClass().getDeclaredField("memberValues");// 因為這個字段事 private final 修飾,所以要打開權限memberValuesField.setAccessible(true);// 獲取 memberValuesMap memberValues = (Map) memberValuesField.get(h);Service service = Stream.of(bean.getClass().getInterfaces()).filter(iface -> iface.getAnnotation(Service.class) != null).collect(Collectors.toList()).get(0).getAnnotation(Service.class);memberValues.put("version", service.version());memberValues.put("group", service.group());} catch (Exception e) {throw new BeanCreationException(String.format("%s %s %s %s %s", "修改", ClassUtils.getQualifiedName(bean.getClass()), "的注解", ClassUtils.getQualifiedName(Service.class), "的 group值和version值出錯"), e);}}return bean; }

?

  參考鏈接:Annotation和動態代理

轉載于:https://www.cnblogs.com/hujunzheng/p/8433980.html

總結

以上是生活随笔為你收集整理的cglib动态代理导致注解丢失问题及如何修改注解允许被继承的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。