springboot 自定义aop
时间: 2023-09-24 19:09:44 浏览: 145
Spring Boot允许我们使用自定义AOP来定制业务逻辑。AOP(面向切面编程)是一种编程范式,可以在不改变原有代码的情况下,对现有代码进行增强。
下面是自定义AOP的步骤:
1. 创建一个切面类,使用@Aspect注解标注该类。该类中需要定义一个或多个切点和通知方法。
```java
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* com.example.demo.service.*.*(..))")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 前置通知
System.out.println("Before method execute...");
// 执行目标方法
Object result = pjp.proceed();
// 后置通知
System.out.println("After method execute...");
return result;
}
}
```
上述代码中,@Pointcut注解定义了一个切点,切点表达式指定了需要增强的方法,这里指定为com.example.demo.service包下的所有方法。@Around注解定义了一个环绕通知方法,该方法在目标方法执行前后分别执行前置通知和后置通知。
2. 在应用程序入口类上添加@EnableAspectJAutoProxy注解,启用Spring的AOP功能。
```java
@SpringBootApplication
@EnableAspectJAutoProxy
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
3. 在需要增强的方法上添加自定义注解,并在切面类中定义一个针对该注解的切点。
```java
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
}
```
```java
@Aspect
@Component
public class MyAspect {
@Pointcut("@annotation(com.example.demo.annotation.MyAnnotation)")
public void pointcut() {
}
@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
// 前置通知
System.out.println("Before method execute...");
// 执行目标方法
Object result = pjp.proceed();
// 后置通知
System.out.println("After method execute...");
return result;
}
}
```
上述代码中,@MyAnnotation注解用于标注需要增强的方法,@Pointcut注解定义一个针对@MyAnnotation注解的切点,@Around注解定义一个环绕通知方法,该方法在目标方法执行前后分别执行前置通知和后置通知。
4. 在需要增强的方法上添加@MyAnnotation注解。
```java
@Service
public class UserServiceImpl implements UserService {
@Override
@MyAnnotation
public void addUser(User user) {
System.out.println("Add user: " + user.getName());
}
}
```
上述代码中,addUser方法上添加了@MyAnnotation注解,表示该方法需要增强。
5. 运行应用程序,观察控制台输出。
```java
Before method execute...
Add user: Alice
After method execute...
```
上述输出结果表明,自定义AOP已经生效,增强逻辑被成功执行。
总结:Spring Boot允许我们使用自定义AOP来定制业务逻辑,可以通过定义切面类、切点、通知方法等方式来实现增强逻辑。在实际应用中,我们可以根据具体需求来制定相应的AOP策略,从而提高应用程序的可扩展性和可维护性。
阅读全文
相关推荐














