1, 什么是 AspectJ?
AspectJ 是一个面向切面的框架, 它扩展了 Java 语言. AspectJ 定义了 AOP 语法, 也可以说 AspectJ 是一个基于 Java 语言的 AOP 框架. 通常我们在使用 Spring AOP 的时候, 都会导入 AspectJ 的相关 jar 包.
在 spring2.0 以后, spring 新增了对 AspectJ 切点表达式的支持; Aspect1.5 新增注解功能, 通过 JDK5 的注解技术, 能直接在类中定义切面; 新版本的 spring 框架, 也都建议使用 AspectJ 来实现 AOP. 所以说在 spring AOP 的核心包 Spring-aop-3.2.jar 里面也有对 AspectJ 的支持.
2, 切入点表达式
- <!-- 切入点表达式 -->
- <aop:pointcut expression="execution(* com.ys.aop.*.*(..))" id="myPointCut"
- />
首先 execution 是 AspectJ 框架定义的一个切入点函数, 其语法形式如下:
execution(modifiers-pattern? ref-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
类修饰符 返回值 方法所在的包 方法名 方法抛出的异常
- <aop:pointcut expression="execution(* com.ys.*Service1.*(..)) ||
- execution(* com.ys.*Service2.*(..))"id="myPointCut"/>
表示匹配 com.ys 包下的, 以 Service1 结尾或者以 Service2 结尾的类的任意方法.
AOP 切入点表达式支持多种形式的定义规则:
1,execution: 匹配方法的执行 (常用)
execution(public *.*(..))
2.within: 匹配包或子包中的方法 (了解)
within(com.ys.aop..*)
3.this: 匹配实现接口的代理对象中的方法 (了解)
this(com.ys.aop.user.UserDAO)
4.target: 匹配实现接口的目标对象中的方法 (了解)
target(com.ys.aop.user.UserDAO)
5.args: 匹配参数格式符合标准的方法 (了解)
args(int,int)
6.bean(id) 对指定的 bean 所有的方法 (了解)
bean('userServiceId')
2,Aspect 通知类型
Aspect 通知类型, 定义了类型名称以及方法格式. 类型如下:
before: 前置通知 (应用: 各种校验)
在方法执行前执行, 如果通知抛出异常, 阻止方法运行
afterReturning: 后置通知 (应用: 常规数据处理)
方法正常返回后执行, 如果方法中抛出异常, 通知无法执行
必须在方法执行后才执行, 所以可以获得方法的返回值.
around: 环绕通知 (应用: 十分强大, 可以做任何事情)
方法执行前后分别执行, 可以阻止方法的执行
必须手动执行目标方法
afterThrowing: 抛出异常通知 (应用: 包装异常信息)
方法抛出异常后执行, 如果方法没有抛出异常, 无法执行
after: 最终通知 (应用: 清理现场)
方法执行完毕后执行, 无论方法中是否出现异常
前置通知 : 在目标方法执行之前执行 [before]
后置通知 : 在目标方法执行之后执行 [after returning]
环绕通知 : 在目标方法执行前和执行后执行 [around]
异常抛出通知: 在目标方法执行出现异常的时候执行 [after throwing]
最终通知 : 无论目标方法是否出现异常最终通知都会执行 [after]
来源: http://www.bubuko.com/infodetail-3099926.html