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!
原文地址:https://www.cnblogs.com/luckygxf/p/15400343.html