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 }

掃描到自定義注解,打印出####

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM