自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

深入了解Spring中的AOP

開(kāi)發(fā) 開(kāi)發(fā)工具
談起AOP,大家都知道是面向切面編程,但你真的了解Spring中的AOP嗎?Spring AOP、JDK動(dòng)態(tài)代理、CGLIB、AspectJ之間又有什么關(guān)聯(lián)和區(qū)別?

 談起AOP,大家都知道是面向切面編程,但你真的了解Spring中的AOP嗎?Spring AOP、JDK動(dòng)態(tài)代理、CGLIB、AspectJ之間又有什么關(guān)聯(lián)和區(qū)別?

[[284151]]

在Spring中AOP包含兩個(gè)概念,一是Spring官方基于JDK動(dòng)態(tài)代理和CGLIB實(shí)現(xiàn)的Spring AOP;二是集成面向切面編程神器AspectJ。Spring AOP和AspectJ不是競(jìng)爭(zhēng)關(guān)系,基于代理的框架的Spring AOP和成熟框架AspectJ都是有價(jià)值的,它們是互補(bǔ)的。

Spring無(wú)縫地將Spring AOP、IoC與AspectJ集成在一起,從而達(dá)到AOP的所有能力。Spring AOP默認(rèn)將標(biāo)準(zhǔn)JDK動(dòng)態(tài)代理用于AOP代理,可以代理任何接口。但如果沒(méi)有面向接口編程,只有業(yè)務(wù)類(lèi),則使用CGLIB。當(dāng)然也可以全部強(qiáng)制使用CGLIB,只要設(shè)置proxy-target-class="true"。

AOP中的術(shù)語(yǔ)

通知(Advice)

Spring切面可以應(yīng)用5種類(lèi)型的通知:

前置通知(Before):在目標(biāo)方法被調(diào)用之前調(diào)用通知功能;

后置通知(After):在目標(biāo)方法完成之后調(diào)用通知,此時(shí)不會(huì)關(guān)心方法的輸出是什么;

返回通知(After-returning):在目標(biāo)方法成功執(zhí)行之后調(diào)用通知;

異常通知(After-throwing):在目標(biāo)方法拋出異常后調(diào)用通知;

環(huán)繞通知(Around):通知包裹了被通知的方法,在被通知的方法調(diào)用之前和調(diào)用之后執(zhí)行自定義的行為。

連接點(diǎn)(Join point)

切點(diǎn)(Poincut)

切面(Aspect)

引入(Introduction)

織入(Weaving)

這些術(shù)語(yǔ)的解釋?zhuān)渌┪闹泻芏?,這里就不再贅述。

用2個(gè)例子來(lái)說(shuō)明Spring AOP和AspectJ的用法

現(xiàn)在有這樣一個(gè)場(chǎng)景,頁(yè)面?zhèn)魅雲(yún)?shù)當(dāng)前頁(yè)page和每頁(yè)展示多少條數(shù)據(jù)rows,我們需要寫(xiě)個(gè)攔截器將page、limit參數(shù)轉(zhuǎn)換成MySQL的分頁(yè)語(yǔ)句offset、rows。

先看Spring AOP實(shí)現(xiàn)

1、實(shí)現(xiàn)MethodInterceptor,攔截方法 

  1. public class MethodParamInterceptor implements MethodInterceptor { 
  2.  
  3. @Override 
  4.  
  5. @SuppressWarnings("unchecked"
  6.  
  7. public Object invoke(MethodInvocation invocation) throws Throwable { 
  8.  
  9. Object[] params = invocation.getArguments(); 
  10.  
  11. if (ArrayUtils.isEmpty(params)) { 
  12.  
  13. return invocation.proceed(); 
  14.  
  15.  
  16. for (Object param : params) { 
  17.  
  18. //如果參數(shù)類(lèi)型是Map 
  19.  
  20. if (param instanceof Map) { 
  21.  
  22. Map paramMap = (Map) param; 
  23.  
  24. processPage(paramMap); 
  25.  
  26. break; 
  27.  
  28.  
  29.  
  30. return invocation.proceed(); 
  31.  
  32.  
  33. /** 
  34.  
  35.  
  36. * @param paramMap 
  37.  
  38. */ 
  39.  
  40. private void processPage(Map paramMap) { 
  41.  
  42. if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) { 
  43.  
  44. return
  45.  
  46.  
  47. int page = 1; 
  48.  
  49. int rows = 10; 
  50.  
  51. for (Map.Entry entry : paramMap.entrySet()) { 
  52.  
  53. String key = entry.getKey(); 
  54.  
  55. String value = entry.getValue().toString(); 
  56.  
  57. if ("page".equals(key)) { 
  58.  
  59. page = NumberUtils.toInt(value, page); 
  60.  
  61. else if ("limit".equals(key)) { 
  62.  
  63. rows = NumberUtils.toInt(value, rows); 
  64.  
  65. }else { 
  66.  
  67. //TODO 
  68.  
  69.  
  70.  
  71. int offset = (page - 1) * rows
  72.  
  73. paramMap.put("offset", offset); 
  74.  
  75. paramMap.put("rows"rows); 
  76.  
  77.  

2、定義后置處理器,將方法攔截件加入到advisor中。我們通過(guò)注解@Controller攔截所有的Controller,@RestController繼承于Controller,所以統(tǒng)一攔截了。 

  1. public class RequestParamPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor 
  2.  
  3. implements InitializingBean { 
  4.  
  5. private Class validatedAnnotationType = Controller.class; 
  6.  
  7. @Override 
  8.  
  9. public void afterPropertiesSet() throws Exception { 
  10.  
  11. Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true); 
  12.  
  13. this.advisor = new DefaultPointcutAdvisor(pointcut, new MethodParamInterceptor()); 
  14.  
  15.  

 

3、萬(wàn)事俱備只欠東風(fēng),Processor也寫(xiě)好了,只需要讓Processor生效。

 

  1. @Configuration 
  2.  
  3. public class MethodInterceptorConfig { 
  4.  
  5. @Bean 
  6.  
  7. public RequestParamPostProcessor converter() { 
  8.  
  9. return new RequestParamPostProcessor(); 
  10.  
  11.  
  12. }` 

這里有個(gè)坑需要注意一下,如果在配置類(lèi)中注入業(yè)務(wù)Bean。 

  1. @Configuration 
  2.  
  3. public class MethodInterceptorConfig { 
  4.  
  5. @Autowired 
  6.  
  7. private UserService userService; 
  8.  
  9. @Bean 
  10.  
  11. public RequestParamPostProcessor converter() { 
  12.  
  13. return new RequestParamPostProcessor(); 
  14.  
  15.  

啟動(dòng)時(shí),會(huì)出現(xiàn):

  1. 2019-11-08 14:55:50.954 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionFactory' of type [org.apache.ibatis.session.defaults.DefaultSqlSessionFactory] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 
  2.  
  3. 2019-11-08 14:55:50.960 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'sqlSessionTemplate' of type [org.mybatis.spring.SqlSessionTemplate] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 
  4.  
  5. 2019-11-08 14:55:51.109 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'rememberMapper' of type [com.sun.proxy.$Proxy84] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 
  6.  
  7. 2019-11-08 14:55:53.406 INFO 51396 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 

很多切面失效,如事務(wù)切面。這是因?yàn)樽⑷肓俗远x的Bean,自定義的Bean優(yōu)先級(jí)最低,由最低優(yōu)先級(jí)的BeanPostProcessor來(lái)加載并完成初始化的。但為了加載其中的RequestParamPostProcessor,導(dǎo)致不得不優(yōu)先裝載低優(yōu)先級(jí)Bean,此時(shí)事務(wù)處理器的AOP等都還沒(méi)完成加載,注解事務(wù)初始化都失敗了。但Spring就提示了一個(gè)INFO級(jí)別的提示,然后剩下的Bean由最低優(yōu)先級(jí)的BeanPostProcessor正常處理。

AspectJ方式實(shí)現(xiàn)切面 

  1. @Component@Aspect@Slf4jpublic class MethodParamInterceptor { 
  2.  
  3.     @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)"
  4.     public void paramAspect() { 
  5.  
  6.     } 
  7.  
  8.  
  9.     @Before("paramAspect()"
  10.     public void beforeDataSource(JoinPoint joinPoint) { 
  11.         Arrays.stream(joinPoint.getArgs()).forEach(paramObject -> { 
  12.             if (paramObject instanceof Map) { 
  13.                 Map parameter = (Map) paramObject; 
  14.                 processPage(parameter); 
  15.             } 
  16.         }); 
  17.  
  18.     } 
  19.  
  20.     private void processPage(Map<String, Object> paramMap) { 
  21.         if (null == paramMap) { 
  22.             return
  23.         } 
  24.         if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) { 
  25.             return
  26.         } 
  27.         int page = 1; 
  28.         int rows = 10; 
  29.         for (Map.Entry<String, Object> entry : paramMap.entrySet()) { 
  30.             String key = entry.getKey(); 
  31.             String value = entry.getValue().toString(); 
  32.             if ("page".equals(key)) { 
  33.                 page = NumberUtils.toInt(value, page); 
  34.             } else if ("limit".equals(key)) { 
  35.                 rows = NumberUtils.toInt(value, rows); 
  36.             } 
  37.         } 
  38.         int offset = (page - 1) * rows
  39.         paramMap.put("offset", offset); 
  40.         paramMap.put("rows"rows); 
  41.     } 
  42.  
  43.  
  44.     @After("paramAspect()"
  45.     public void afterDataSource(JoinPoint joinPoint) { 
  46.  
  47.     } 

從上面兩個(gè)例子可以對(duì)比出SpringAOP和AspectJ的兩種不同用法,但達(dá)到的能力是一樣的。

Sping AOP在組織、抽象代碼場(chǎng)景中更加適合,AspectJ用于單純的切面來(lái)實(shí)現(xiàn)某項(xiàng)功能更加簡(jiǎn)潔。

【本文是51CTO專(zhuān)欄機(jī)構(gòu)“舟譜數(shù)據(jù)”的原創(chuàng)文章,微信公眾號(hào)“舟譜數(shù)據(jù)( id: zhoupudata)”】 

戳這里,看該作者更多好文

 

責(zé)任編輯:華軒 來(lái)源: 51CTO
相關(guān)推薦

2017-01-20 08:30:19

JavaScriptfor循環(huán)

2024-04-12 07:51:05

SpringBean初始化

2024-03-07 16:12:46

Java字符串線(xiàn)程

2010-11-19 16:22:14

Oracle事務(wù)

2010-07-13 09:36:25

2010-06-23 20:31:54

2009-08-25 16:27:10

Mscomm控件

2020-09-21 09:53:04

FlexCSS開(kāi)發(fā)

2022-08-26 13:48:40

EPUBLinux

2020-07-20 06:35:55

BashLinux

2019-08-02 08:59:21

Token認(rèn)證服務(wù)器

2013-04-10 11:16:19

iPad的MouseE

2018-02-24 13:21:02

2018-09-04 16:20:46

MySQ索引數(shù)據(jù)結(jié)構(gòu)

2016-10-20 08:46:17

2021-09-03 08:27:47

FortinetSASE平臺(tái)安全

2010-11-15 11:40:44

Oracle表空間

2022-06-03 10:09:32

威脅檢測(cè)軟件

2011-07-18 15:08:34

2013-04-16 10:20:21

云存儲(chǔ)服務(wù)云存儲(chǔ)SLA服務(wù)水平協(xié)議
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)