深入了解Spring中的AOP
談起AOP,大家都知道是面向切面編程,但你真的了解Spring中的AOP嗎?Spring AOP、JDK動態代理、CGLIB、AspectJ之間又有什么關聯和區別?
在Spring中AOP包含兩個概念,一是Spring官方基于JDK動態代理和CGLIB實現的Spring AOP;二是集成面向切面編程神器AspectJ。Spring AOP和AspectJ不是競爭關系,基于代理的框架的Spring AOP和成熟框架AspectJ都是有價值的,它們是互補的。
Spring無縫地將Spring AOP、IoC與AspectJ集成在一起,從而達到AOP的所有能力。Spring AOP默認將標準JDK動態代理用于AOP代理,可以代理任何接口。但如果沒有面向接口編程,只有業務類,則使用CGLIB。當然也可以全部強制使用CGLIB,只要設置proxy-target-class="true"。
AOP中的術語
通知(Advice)
Spring切面可以應用5種類型的通知:
前置通知(Before):在目標方法被調用之前調用通知功能;
后置通知(After):在目標方法完成之后調用通知,此時不會關心方法的輸出是什么;
返回通知(After-returning):在目標方法成功執行之后調用通知;
異常通知(After-throwing):在目標方法拋出異常后調用通知;
環繞通知(Around):通知包裹了被通知的方法,在被通知的方法調用之前和調用之后執行自定義的行為。
連接點(Join point)
切點(Poincut)
切面(Aspect)
引入(Introduction)
織入(Weaving)
這些術語的解釋,其他博文中很多,這里就不再贅述。
用2個例子來說明Spring AOP和AspectJ的用法
現在有這樣一個場景,頁面傳入參數當前頁page和每頁展示多少條數據rows,我們需要寫個攔截器將page、limit參數轉換成MySQL的分頁語句offset、rows。
先看Spring AOP實現
1、實現MethodInterceptor,攔截方法
- public class MethodParamInterceptor implements MethodInterceptor {
- @Override
- @SuppressWarnings("unchecked")
- public Object invoke(MethodInvocation invocation) throws Throwable {
- Object[] params = invocation.getArguments();
- if (ArrayUtils.isEmpty(params)) {
- return invocation.proceed();
- }
- for (Object param : params) {
- //如果參數類型是Map
- if (param instanceof Map) {
- Map paramMap = (Map) param;
- processPage(paramMap);
- break;
- }
- }
- return invocation.proceed();
- }
- /**
- *
- * @param paramMap
- */
- private void processPage(Map paramMap) {
- if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) {
- return;
- }
- int page = 1;
- int rows = 10;
- for (Map.Entry entry : paramMap.entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue().toString();
- if ("page".equals(key)) {
- page = NumberUtils.toInt(value, page);
- } else if ("limit".equals(key)) {
- rows = NumberUtils.toInt(value, rows);
- }else {
- //TODO
- }
- }
- int offset = (page - 1) * rows;
- paramMap.put("offset", offset);
- paramMap.put("rows", rows);
- }
- }
2、定義后置處理器,將方法攔截件加入到advisor中。我們通過注解@Controller攔截所有的Controller,@RestController繼承于Controller,所以統一攔截了。
- public class RequestParamPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor
- implements InitializingBean {
- private Class validatedAnnotationType = Controller.class;
- @Override
- public void afterPropertiesSet() throws Exception {
- Pointcut pointcut = new AnnotationMatchingPointcut(this.validatedAnnotationType, true);
- this.advisor = new DefaultPointcutAdvisor(pointcut, new MethodParamInterceptor());
- }
- }
3、萬事俱備只欠東風,Processor也寫好了,只需要讓Processor生效。
- @Configuration
- public class MethodInterceptorConfig {
- @Bean
- public RequestParamPostProcessor converter() {
- return new RequestParamPostProcessor();
- }
- }`
這里有個坑需要注意一下,如果在配置類中注入業務Bean。
- @Configuration
- public class MethodInterceptorConfig {
- @Autowired
- private UserService userService;
- @Bean
- public RequestParamPostProcessor converter() {
- return new RequestParamPostProcessor();
- }
- }
啟動時,會出現:
- 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)
- 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)
- 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)
- 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)
很多切面失效,如事務切面。這是因為注入了自定義的Bean,自定義的Bean優先級最低,由最低優先級的BeanPostProcessor來加載并完成初始化的。但為了加載其中的RequestParamPostProcessor,導致不得不優先裝載低優先級Bean,此時事務處理器的AOP等都還沒完成加載,注解事務初始化都失敗了。但Spring就提示了一個INFO級別的提示,然后剩下的Bean由最低優先級的BeanPostProcessor正常處理。
AspectJ方式實現切面
- @Component@Aspect@Slf4jpublic class MethodParamInterceptor {
- @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
- public void paramAspect() {
- }
- @Before("paramAspect()")
- public void beforeDataSource(JoinPoint joinPoint) {
- Arrays.stream(joinPoint.getArgs()).forEach(paramObject -> {
- if (paramObject instanceof Map) {
- Map parameter = (Map) paramObject;
- processPage(parameter);
- }
- });
- }
- private void processPage(Map<String, Object> paramMap) {
- if (null == paramMap) {
- return;
- }
- if (!paramMap.containsKey("page") && !paramMap.containsKey("limit")) {
- return;
- }
- int page = 1;
- int rows = 10;
- for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
- String key = entry.getKey();
- String value = entry.getValue().toString();
- if ("page".equals(key)) {
- page = NumberUtils.toInt(value, page);
- } else if ("limit".equals(key)) {
- rows = NumberUtils.toInt(value, rows);
- }
- }
- int offset = (page - 1) * rows;
- paramMap.put("offset", offset);
- paramMap.put("rows", rows);
- }
- @After("paramAspect()")
- public void afterDataSource(JoinPoint joinPoint) {
- }
- }
從上面兩個例子可以對比出SpringAOP和AspectJ的兩種不同用法,但達到的能力是一樣的。
Sping AOP在組織、抽象代碼場景中更加適合,AspectJ用于單純的切面來實現某項功能更加簡潔。
【本文是51CTO專欄機構“舟譜數據”的原創文章,微信公眾號“舟譜數據( id: zhoupudata)”】