zoukankan      html  css  js  c++  java
  • Spring 前置和后置处理器

    今天处理一个问题,需要扫描java方法上面自定义注解。代码使用的spring后置处理器BeanPostProcessor.java的postProcessAfterInitialization(),方法代码如下

    1     @Override
    2     @Retryable(value = Exception.class, maxAttempts = 5, backoff = @Backoff(delay = 3000, multiplier = 2, maxDelay = 20000))
    3     @CustomAnnotation
    4     public void testRetry() {
    5         System.out.println("in test retry: " + System.currentTimeMillis() / 1000);
    6         int a = 1 / 0;
    7         System.out.println("end in test retry");
    8     }

    有两个注解一个自定义、一个spring重试的注解。

    后置处理器代码:

     1 @Component
     2 public class CustomBeanProcessor implements BeanPostProcessor {
     3     @Override
     4     public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
     5         Method[] methods = bean.getClass().getDeclaredMethods();
     6         for (Method method : methods) {
     7             CustomAnnotation customAnnotation = method.getAnnotation(CustomAnnotation.class);
     8             if (beanName.equals("retryServiceImpl"))
     9                 System.out.println("beanName:" + beanName + ", method name: " + method.getName() + ", customAnnotation: " + customAnnotation);
    10             if (customAnnotation != null) {
    11                 System.out.println("##############");
    12             }
    13         }
    14         return bean;
    15     }
    16 }

    预期希望进入11行,输出#####。实际没有输出,通过9行打印bean和对应的方法

     有cglib关键字和一些spring生成的方法。可以判断spring通过cglib生成了其他方法,也影响到了注解的扫描。

    修改为使用前置处理器,这个时候bean还没有被初始化,应该还没有被cglib处理。修改为前置处理器

     1 @Component
     2 public class CustomBeanProcessor implements BeanPostProcessor {
     3     @Override
     4     public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
     5         Method[] methods = bean.getClass().getDeclaredMethods();
     6         for (Method method : methods) {
     7             CustomAnnotation customAnnotation = method.getAnnotation(CustomAnnotation.class);
     8             if (beanName.equals("retryServiceImpl"))
     9                 System.out.println("beanName:" + beanName + ", method name: " + method.getName() + ", customAnnotation: " + customAnnotation);
    10             if (customAnnotation != null) {
    11                 System.out.println("##############");
    12             }
    13         }
    14         return bean;
    15     }
    16 }

    扫描到自定义注解,打印出####

    Please call me JiangYouDang!
  • 相关阅读:
    excel多个工作表数据快速合并到一个工作表方法
    客商申请单客商编码自动编码
    如何实现Excel多人共享与协作
    商家推销技巧-将广告做成实用信息
    如何实现扫码填报信息
    DBSync如何连接并同步MySQL
    如何在微信中发布动态信息
    一款数据库比较与同步软件的设计与实现
    【原创】在 ASP.NET Core 3.1 中使用 Senparc.Weixin.Work 企业微信 SDK —— 发送文本消息
    【原创】在 .NET Core 3.1 中使用 Senparc.Weixin.Work 企业微信 SDK —— 发送文本消息
  • 原文地址:https://www.cnblogs.com/luckygxf/p/15400343.html
Copyright © 2011-2022 走看看