ava中aop的代码实例
时间: 2023-09-24 15:11:20 浏览: 54
以下是一个使用Spring AOP的Java代码实例:
```
package com.example.aopdemo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class LoggingAspect {
// 定义切点
@Pointcut("execution(* com.example.aopdemo.*.*(..))")
private void forAllMethods() {}
// 前置通知
@Before("forAllMethods()")
public void beforeAdvice(JoinPoint joinPoint) {
System.out.println("调用方法前:" + joinPoint.getSignature());
}
// 后置通知
@AfterReturning(pointcut = "forAllMethods()", returning = "result")
public void afterAdvice(JoinPoint joinPoint, Object result) {
System.out.println("调用方法后:" + joinPoint.getSignature() + ",返回值为:" + result);
}
}
```
这个例子中,我们定义了一个名为 `LoggingAspect` 的切面,它拦截了 `com.example.aopdemo` 包下的所有方法,即切点 `forAllMethods()`。在这个切面中,我们定义了两个通知,一个前置通知 `beforeAdvice()` 和一个后置通知 `afterAdvice()`,它们分别在目标方法调用前和调用后执行。在这两个通知中,我们都使用了 `JoinPoint` 对象来获取目标方法的签名和返回值。