OOP是面向切面编程,AOP是面向切面编程。
这两个有什么区别呢,我的理解是这样的,oop就是给我一个功能我一条路写到黑,我不管我只要实现。
aop不一样,我的理解就是不同功能就抽出来,比如日志,事务抽出来,要用的时候组装一下就可以实现你这个功能,oop就是我的逻辑里面就也会有日志啊,事务的问题。当然只有正真看到代码才能感受其中的奥妙!
1.1 AOP的优势- 提高代码的重用性
- 业务代码的简洁
- 业务代码维护更高效
- 业务功能扩展更便捷
这边的Logs就是我的通知类。也就是共性方法,抽取出来了。
2. Aop 特性 2.1 切点表达式这边大概讲一下,怎么匹配的,有个印象就行,到时候分析不出来就百度问!
2.1.1切入点类型这边就简单概述一下,其实就是全局切入点和局部切入点和私有切入点
为啥这边切入点要首先介绍呢,这个还是比较重要的,到时候可能存在该切入的没有匹配上,不该切入的切入了。所以正常用AOP的公司规范特别重要,什么包名,类名,方法名。乱写的话根本玩不转。
2.2 通知类型下面着重介绍一下环绕通知
通知顺序的问题是看配置的顺序,配置的顺序决定着通知的顺序
2.3 通知获取切点的入参和返回值以及处理异常这个非常重要,需要认真看
第一种获取参数的方法
这是第二种获取的方法
获取返回值
处理异常
3. AOP注解这边就直接贴代码比较直观了
package com.zx.Aop;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAop {
@Pointcut("execution(* *..*(..))")
public void Mypt(){
}
public void logs(){
System.out.println("开始请求方法!日志功能");
}
@Before("Mypt()")
public void before(JoinPoint joinPoint){
Object[] args = joinPoint.getArgs();
System.out.println("开始请求方法!before..."+ args[0]);
}
@Before(value = "MyPointAop.py2() && args(joinPoint)")
public void before1(int joinPoint){
System.out.println("开始请求方法!before1..."+ joinPoint);
}
@After("Mypt()")
public void after(){
System.out.println("开始请求方法!after");
}
@AfterReturning(value = "Mypt()",returning = "rets")
public void afterReturning(Object rets){
System.out.println("开始请求方法!afterReturning" + rets);
}
@AfterThrowing(value = "Mypt()",throwing = "throwable")
public void afterThrowing(Throwable throwable){
System.out.println("开始请求方法!afterThrowing" + throwable.getMessage());
}
@Around("Mypt()")
public Object around(ProceedingJoinPoint point) {
System.out.println("开始请求方法!aroundBefore");
Object proceed = null;
try {
proceed = point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("开始请求方法!aroundAfter");
return proceed;
}
}
这边贴几个注意事项
3.1 aop注解执行顺序 3.2 注解配置方法 4.最后一个小tips @Around("Mypt()")
public Object around(ProceedingJoinPoint point) {
//这个对象有很多有意思的数据,感兴趣的可以打印一下
Signature signature = point.getSignature();
System.out.println(signature.toLongString());
System.out.println("开始请求方法!aroundBefore");
Object proceed = null;
try {
proceed = point.proceed();
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("开始请求方法!aroundAfter");
return proceed;
}



