Around Advice里的通知解析和Before Advice解析都是放在MethodBeforeAdviceInterceptor
时间: 2023-12-06 12:41:31 浏览: 30
其实,在 Spring AOP 中,通知(Advice)是通过拦截器(Interceptor)来实现的。MethodBeforeAdviceInterceptor 是一个拦截器,用于实现 Before Advice,也就是在目标方法执行之前执行的通知。
MethodBeforeAdviceInterceptor 中的通知解析和前置通知解析是在拦截器链中的一个环节,它会在目标方法执行之前先执行。具体来说,当目标方法被调用时,Spring AOP 会按照指定的顺序依次执行所有的拦截器,其中 MethodBeforeAdviceInterceptor 就是其中之一。在执行 MethodBeforeAdviceInterceptor 时,它会首先解析出需要执行的前置通知,并将其保存在当前的拦截器链对象中。然后,在目标方法执行之前,MethodBeforeAdviceInterceptor 就会调用该前置通知进行处理。
需要注意的是,MethodBeforeAdviceInterceptor 只是拦截器链中的一个环节,它只负责实现 Before Advice。如果还需要实现其他类型的通知,例如 Around Advice、After Returning Advice、After Throwing Advice 等,就需要添加对应的拦截器。这些拦截器会按照指定的顺序依次执行,从而实现完整的 AOP 功能。
相关问题
java中advice是什么
在Java中,Advice(通知)是切面编程中的一个术语,它是指在特定的切点(Join Point)上执行的操作。通常,Advice会在方法调用前、方法调用后或方法抛出异常时执行一些额外的操作。
在Spring框架中,Advice是AOP编程的基本元素之一,它可以在方法调用前、方法调用后、方法返回后以及方法抛出异常时执行一些额外的操作,如事务管理、安全检查、日志记录等。
Spring框架中提供了五种类型的Advice:
1. 前置通知(Before Advice):在目标方法调用前执行的通知。
2. 后置通知(After Advice):在目标方法调用后执行的通知。
3. 返回通知(After Returning Advice):在目标方法成功执行后执行的通知。
4. 异常通知(After Throwing Advice):在目标方法抛出异常后执行的通知。
5. 环绕通知(Around Advice):在目标方法调用前后都执行的通知。
通过使用Advice,我们可以将一些通用的代码逻辑从业务逻辑中分离出来,提高代码的可重用性和可维护性。同时,Advice还可以对业务逻辑进行补充和增强,从而实现更加灵活和强大的业务逻辑。
Caused by: java.lang.IllegalArgumentException: ProceedingJoinPoint is only supported for around advice
这个异常是因为你在使用 Spring AOP 的时候,将非 around 类型的通知(例如:@Before,@After,@AfterReturning,@AfterThrowing)应用到了 ProceedingJoinPoint 参数上。
ProceedingJoinPoint 参数只能在 around 类型的通知中使用,因为它允许你控制方法的执行过程(包括是否执行方法和如何修改方法的返回值)。所以,如果你想要在通知中使用 ProceedingJoinPoint 参数,你需要将通知的类型修改为 around。
例如,以下代码会导致该异常:
```java
@Before("execution(* com.example.service.*.*(..))")
public void before(ProceedingJoinPoint joinPoint) {
// ...
}
```
要解决这个异常,你可以将通知类型修改为 around,例如:
```java
@Around("execution(* com.example.service.*.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// ...
return joinPoint.proceed();
}
```
这样,你就可以在通知中使用 ProceedingJoinPoint 参数了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)