SpringAOP核心概念
AOP是Spring的关键之一,面向切面编程,Spring AOP模块提供截取拦截应用程序的拦截器,例如,当执行方法时,可以在执行方法之前或之后添加额外的功能,比如,日志记录,权限管理,声明式事务,安全性和缓存等。
AOP术语
切面(Aspect):定义一个切面,一个具有一组API的模块,提供交叉要求。例如,日志记录模块被称为AOP方面用于记录。应用程序可以根据需要具有任意数量的切面。
连接点(JoinPoint):表示可以插入切面的一个位置,或者说这是程序中可以使用SpringAOP切入的实际位置。
通知(Advice):这是在方法执行之前或之后采取的实际操作,是在SpringAOP框架的程序执行期间调用的实际代码片段。
切入点(PointCut):这是一组一个或多个连接点,其中应该执行通知(Advice)。
引入(Introduction):在不修改代码的前提下,引入可以在运行期为类动态地添加一些方法或字段。
目标对象(Targetobject):对象被一个或多个切面通知(Advice),该对象将始终是代理的对象。也称为通知(Advice)对象。
编织(Weaving):编织是将切面与其他应用程序类型或对象进行链接以创建通知(Advice)对象的过程。 这可以在编译时,加载时间或运行时完成。
SpringAOP通知类型
before:在方法执行之前运行通知。
after:在方法执行之后运行通知,无论其结果如何。
after-returning:只有在方法成功完成后才能在方法执行后运行通知。
after-throwing:只有在方法通过抛出异常而退出方法执行之后才能运行通知。
around:在调用通知方法之前和之后运行通知,通用。
SpringAOP实现
基于@AspectJ
1、 声明一个切面(aspect)
import org.aspectj.lang.annotation.Aspect;
@Aspect
public class AspectModule {
}
2、 声明一个切入点(PointCut)
切入点(pointcut)有助于确定要用不同通知执行的关联点(即方法)。在使用基于@AspectJ的配置时,切入点声明有两部分:
- 一个切入点表达式,确定哪些方法执行。
- 切入点签名包括名称和任意数量的参数。 该方法的实体是无关紧要的,也可以是空的。
以下示例定义了一个名为** businessService** 和getname 的切入点,该切入点将匹配com.xyz.myapp.service包下的类中可用的每个方法的执行:
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.xyz.myapp.service.*.*(..))") // expression
private void businessService() {} // signature
import org.aspectj.lang.annotation.Pointcut;
@Pointcut("execution(* com.yiibai.Student.getName(..))")
private void getname() {}
3、声明通知
这个通知就是上篇文章中写到的那五种通知方式,建议代码如下
@Before("businessService()")
public void doBeforeTask(){
...
}
@After("businessService()")
public void doAfterTask(){
...
}
@AfterReturning(pointcut = "businessService()", returning="retVal")
public void doAfterReturnningTask(Object retVal){
// you can intercept retVal here.
...
}
@AfterThrowing(pointcut = "businessService()", throwing="ex")
public void doAfterThrowingTask(Exception ex){
// you can intercept thrown exception here.
...
}
@Around("businessService()")
public void doAroundTask(){
...
}
可以为任何通知定义切入点内嵌,如下
@Before("execution(* com.xyz.myapp.service.*.*(..))")
public doBeforeTask(){
...
}
AOP主要应用场景
- Authentication 权限
- Caching 缓存
- Context passing 内容传递
- Error handling 错误处理
- Lazy loading 懒加载
- Debugging 调试
- logging, tracing, profiling and monitoring 记录跟踪 优化 校准
- Performance optimization 性能优化
- Persistence 持久化
- Resource pooling 资源池
- Synchronization 同步
- Transactions 事务