AOP

  1. 引入依赖
<dependencies>
    <!-- Spring AOP 依赖 -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>5.3.10</version>
    </dependency>
    <!-- AspectJ 依赖 -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.7</version>
    </dependency>
</dependencies>
  1. 创建业务服务类
    创建一个简单的业务服务类 MyService,其中包含一个方法 performTask,这个方法将在 AOP 中被拦截。
@Service
public class MyService {

    public void performTask() {
        System.out.println("Performing task...");
    }
}
  1. 创建切面类
    创建一个切面类 LoggingAspect,在这个类中定义前置通知和环绕通知。
@Aspect
@Component
public class LoggingAspect {

    // 前置通知
    @Before("execution(* com.example.aop.MyService.performTask(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Before " + joinPoint.getSignature().getName() + " method");
    }

    // 环绕通知
    @Around("execution(* com.example.aop.MyService.performTask(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around before " + joinPoint.getSignature().getName() + " method");
        try {
            // 执行目标方法
            Object result = joinPoint.proceed();
            System.out.println("Around after " + joinPoint.getSignature().getName() + " method");
            return result;
        } catch (Exception e) {
            System.out.println("Exception occurred: " + e.getMessage());
            throw e;
        }
    }
}
  1. 配置 Spring 应用程序
    Spring 自动扫描组件并启用 AOP,创建一个配置类 AppConfig
@Configuration
@ComponentScan(basePackages = "com.example.aop")
@EnableAspectJAutoProxy
public class AppConfig {
}
posted @ 2025-01-22 17:48  Look_Back  阅读(7)  评论(0)    收藏  举报