怎么添加spring aop
时间: 2023-03-25 13:04:26 浏览: 110
您可以通过以下步骤添加 Spring AOP:
1. 在 pom.xml 文件中添加 Spring AOP 依赖项:
```
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.3.9</version>
</dependency>
```
2. 创建一个切面类,该类包含一个或多个切点和通知:
```
@Aspect
@Component
public class LoggingAspect {
@Pointcut("execution(* com.example.myapp.service.*.*(..))")
private void serviceMethods() {}
@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void logAfterReturning(JoinPoint joinPoint, Object result) {
System.out.println("After method execution: " + joinPoint.getSignature().getName());
}
}
```
3. 在 Spring 配置文件中启用 AOP:
```
<aop:aspectj-autoproxy />
```
4. 在需要使用 AOP 的类中注入切面类:
```
@Service
public class MyService {
@Autowired
private LoggingAspect loggingAspect;
public void doSomething() {
// ...
}
}
```
这样,当 MyService 的 doSomething() 方法被调用时,LoggingAspect 中定义的通知将被执行。