面向切面编程的一种方式
1 配置扫描
2 通过注解切面
*/
@Aspect
@Component
public class Aop {
private void aop(JoinPoint joinPoint, String s) {
Signature signature = joinPoint.getSignature();
String methonName = signature.getName();
Object[] args = joinPoint.getArgs();
System.out.println(getClass().getName() + s + ",方法名字:" + methonName + ",参数列表:" + List.of(args));
}
@Pointcut(value = "execution( public * spring.anntation.aop.dynamicProxy.CalculateImpl.*(..))")
private void beforeDoPoint() {
}
@Around(value = "beforeDoPoint()")
private Object around(ProceedingJoinPoint proceedingJoinPoint) {
System.out.println("环绕执行方法前");
Signature signature = proceedingJoinPoint.getSignature();
//方法名字
String mothodName = signature.getName();
//参数列表
Object[] args = proceedingJoinPoint.getArgs();
Object result = null;
try {
//方法执行
result = proceedingJoinPoint.proceed(args);
System.out.println("环绕执行方法返回" + result);
} catch (Throwable e) {
e.printStackTrace();
String message = e.getMessage();
if (message == null) {
message = e.getCause().getMessage();
}
System.out.println("环绕方法异常" + message);
//抛出去让afterThrowing捕捉
throw new RuntimeException(message);
} finally {
System.out.println("环绕方法后置");
}
return result;
}
@AfterThrowing(value = "beforeDoPoint()", throwing = "e")
private void beforeThrow(JoinPoint joinPoint, Exception e) {
aop(joinPoint, "异常通知");
System.out.println(e);
// throw new RuntimeException(e);
}
@AfterReturning(value = "beforeDoPoint()", returning = "result")
public Object afterReturn(JoinPoint joinPoint, Object result) {
aop(joinPoint, "返回通知");
System.out.println("返回通知" + result);
return result;
}
@After(value = "beforeDoPoint()")
public void afterDo(JoinPoint joinPoint) {
aop(joinPoint, "后置通知");
}
@Before(value = "beforeDoPoint()")
public void beforeDo3(JoinPoint joinPoint) {
aop(joinPoint, "前置通知");
}
// @Before(value = "execution(public int spring.anntation.aop.dynamicProxy.CalculateImpl.add(int, int))")
// public void beforeDo2(JoinPoint joinPoint) {
// Signature signature = joinPoint.getSignature();
// String methonName = signature.getName();
// Object[] args = joinPoint.getArgs();
// System.out.println(getClass().getName() + "前置通知,方法名字:" + methonName + ",参数列表:" + List.of(args));
// }
}