springboot 使用aop
时间: 2023-12-02 20:43:14 浏览: 91
以下是使用SpringBoot AOP的步骤:
1. 首先,在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
```
2. 创建一个切面类,使用@Aspect注解标记该类,并在该类中定义切点和通知。
```java
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.demo.service.*.*(..))")
public void pointcut() {}
@Before("pointcut()")
public void before(JoinPoint joinPoint) {
System.out.println("Before method: " + joinPoint.getSignature().getName()); }
@After("pointcut()")
public void after(JoinPoint joinPoint) {
System.out.println("After method: " + joinPoint.getSignature().getName());
}
}
```
3. 在应用程序主类上添加@EnableAspectJAutoProxy注解,启用自动代理。
```java
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
4. 在需要使用AOP的类或方法上添加自定义注解,并在切面类中使用@Around注解来拦截该注解。
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {}
@Around("@annotation(com.example.demo.aspect.MyAnnotation)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("Before method: " + joinPoint.getSignature().getName());
Object result = joinPoint.proceed();
System.out.println("After method: " + joinPoint.getSignature().getName());
return result;
}
@Service
public class MyService {
@MyAnnotation
public void doSomething() {
System.out.println("Doing something...");
}
}
```
阅读全文