[Spring]Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用

本文主要是介绍[Spring]Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用

一、5种切入方式

学习了下Spring的AOP的五种切入方式,分别是:

(1)Before ---在所拦截方法执行前执行;

(2)After ---在所拦截方法执行后执行;

(3)AfterRuturning  ---在所拦截方法返回值后,执行;

(4)AfterThrowing ---当所拦截方法抛出异常时,执行;

(5)Around ---最为复杂的切入方式,刚方式可以包括上述4个方式。


现在假设切入点为A_Method(假设该方法的执行输出为“A”)。

方式(1)的切入方式的结果为:

             before

             A


方式(2)的切入方式的结果为:

             A

     after


方式(3)的切入方式的结果为:

             A

    afterreturning

方式(4)的切入方式的结果为:

         (有异常,则抛出,执行)


方式(5)的切入方式的结果为:

         可以是上述四种的任意组合。


对于方式(2)(3),是一样的么?其实不然。

区别:拦截方法不管是否有异常,都会执行的是方式(2),即After的切入方式。类似于try-catch-finally,在finally里面的语句。而方式(3)只有当拦截方法成功执行才会执行。

可通过有异常的方法来测试区别(笔者采用的是除0异常)。


二、AOP优先级

如果同时有2个AOP切面,那么如何设定优先级呢?Spring提供了“@order()”的注解方式,@order(1)则表示优先级最高,order(n),n越小,优先级越高。如下例。


图1


图2


图2的加载是优于图1的。 


三、切面表达式的重用

我们发现,添加注解时,我们有相同的内容,这样的东西是否可以重用呢?答案是肯定的。

通过@Pointcut()即可完成切面表达式的重用。如下例。

import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(3)
@Aspect
@Component
public class testAspect {@Pointcut("execution(* com.spring.aop.test1.*.*(int,int))")public void asp(){}@Before("asp()")public void beforeMethod(JoinPoint joinpoint){Object name = joinpoint.getSignature().getName();Object[] list = joinpoint.getArgs();System.out.println("before.."+name+":"+Arrays.asList(list));}@After("asp()")public void afterMethod(){System.out.println("after..");}@AfterReturning("asp()")public void afterReturningMethod(){System.out.println("afterreturn..");}}


四、AOP的XML配置方式

上一篇记录了AOP的5种切入方式,但是所有的bean都是基于注解的方式来添加进容器的,这一节采用配置文件方式进行配置。贴上代码。如下。

package com.spring.aop.test3;public interface jisuan {public int add(int i,int j);public int mul(int i,int j);public int sub(int i,int j);public int div(int i,int j);
}

package com.spring.aop.test3;public class jisuanimpl implements jisuan {@Overridepublic int add(int i, int j) {// TODO Auto-generated method stub
//		System.out.println("add is begin..");//mul,sub,div都是int result = i+j;System.out.println(result);
//		System.out.println("add is over..");return result;}@Overridepublic int mul(int i, int j) {// TODO Auto-generated method stubint result = i*j;System.out.println(result);return result;}@Overridepublic int sub(int i, int j) {// TODO Auto-generated method stubint result = i-j;System.out.println(result);return result;}@Overridepublic int div(int i, int j) {// TODO Auto-generated method stubint result = i/j;System.out.println(result);return result;}}

package com.spring.aop.test3;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans-aop-2.xml");jisuan js = (jisuan) ctx.getBean("js"); js.add(4, 2);}
}

package com.spring.aop.test3;import java.util.Arrays;import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;public class testAspect {public void asp() {}public void beforeMethod(JoinPoint joinpoint) {Object name = joinpoint.getSignature().getName();Object[] list = joinpoint.getArgs();System.out.println("before.." + name + ":" + Arrays.asList(list));}public void afterMethod() {System.out.println("after..");}public void afterReturningMethod() {System.out.println("afterreturn..");}public int aroundMethod(ProceedingJoinPoint pjp) {int result = 0;try {System.out.println("before method..");result=(int) pjp.proceed();System.out.println("afterreturning method..");} catch (Exception e) {System.out.println("throwable exception..");// TODO Auto-generated catch blocke.printStackTrace();} catch (Throwable e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("after method..");return result;}}


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"><bean id="js" class="com.spring.aop.test3.jisuanimpl"></bean><bean id="testAspect" class="com.spring.aop.test3.testAspect"></bean><!-- 配置AOP --><aop:config><!-- 配置切面表达式 --><aop:pointcut expression="execution(* com.spring.aop.test3.*.*(int,int))"id="point" /><aop:aspect ref="testAspect" order="1"><!-- 	<aop:before method="beforeMethod" pointcut-ref="point" /><aop:after method="afterMethod" pointcut-ref="point"/> --><!-- 环绕通知 --><aop:around method="aroundMethod" pointcut-ref="point"/></aop:aspect></aop:config>
</beans>


下面的为运行结果。



在编写@around的method遇到错误: Exception in thread "main"org.springframework.aop.AopInvocationException: Null return value from advice does not match primitive return type for: ........

原因是,@around()方法指定的方法的返回值类型必须是和拦截方法的返回值数据类型一致。本例的add()、mul()等方法的返回类型为int,那么@around()指定的方法的返回类型必须是int,不然会报上面的错。

---------------------分割线----------------------------


2016年6月21日,在华为实习期间,使用Spring AOP解决了记录日志的功能。

特此记录一些心得:

(1)这篇我所写的博文,时隔一年再来看,内容较为粗糙

(2)AOP的配置,可以仅仅通过XML进行配置,也可以通过注解的方式进行配置。

(3)配置如@Around等切入方式的方法,其返回类型应与切入点保持一致,这一点在其他很多博文中都没有看到有所体现。这里需要注意下。

这篇关于[Spring]Spring AOP学习笔记(2)---5种切入方式、AOP优先级及切面表达式的重用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/196364

相关文章

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

springboot项目中常用的工具类和api详解

《springboot项目中常用的工具类和api详解》在SpringBoot项目中,开发者通常会依赖一些工具类和API来简化开发、提高效率,以下是一些常用的工具类及其典型应用场景,涵盖Spring原生... 目录1. Spring Framework 自带工具类(1) StringUtils(2) Coll

SpringValidation数据校验之约束注解与分组校验方式

《SpringValidation数据校验之约束注解与分组校验方式》本文将深入探讨SpringValidation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可... 目录引言一、Spring Validation基础架构1.1 jsR-380标准与Spring整合1

SpringBoot条件注解核心作用与使用场景详解

《SpringBoot条件注解核心作用与使用场景详解》SpringBoot的条件注解为开发者提供了强大的动态配置能力,理解其原理和适用场景是构建灵活、可扩展应用的关键,本文将系统梳理所有常用的条件注... 目录引言一、条件注解的核心机制二、SpringBoot内置条件注解详解1、@ConditionalOn

通过Spring层面进行事务回滚的实现

《通过Spring层面进行事务回滚的实现》本文主要介绍了通过Spring层面进行事务回滚的实现,包括声明式事务和编程式事务,具有一定的参考价值,感兴趣的可以了解一下... 目录声明式事务回滚:1. 基础注解配置2. 指定回滚异常类型3. ​不回滚特殊场景编程式事务回滚:1. ​使用 TransactionT

Android实现打开本地pdf文件的两种方式

《Android实现打开本地pdf文件的两种方式》在现代应用中,PDF格式因其跨平台、稳定性好、展示内容一致等特点,在Android平台上,如何高效地打开本地PDF文件,不仅关系到用户体验,也直接影响... 目录一、项目概述二、相关知识2.1 PDF文件基本概述2.2 android 文件访问与存储权限2.

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Spring Shell 命令行实现交互式Shell应用开发

《SpringShell命令行实现交互式Shell应用开发》本文主要介绍了SpringShell命令行实现交互式Shell应用开发,能够帮助开发者快速构建功能丰富的命令行应用程序,具有一定的参考价... 目录引言一、Spring Shell概述二、创建命令类三、命令参数处理四、命令分组与帮助系统五、自定义S

SpringSecurity JWT基于令牌的无状态认证实现

《SpringSecurityJWT基于令牌的无状态认证实现》SpringSecurity中实现基于JWT的无状态认证是一种常见的做法,本文就来介绍一下SpringSecurityJWT基于令牌的无... 目录引言一、JWT基本原理与结构二、Spring Security JWT依赖配置三、JWT令牌生成与