【项目实战】从AOP到AspectJ入门介绍

一、AOP介绍

1.1 AOP是什么?

AOP是Aspect Oriented Programming的缩写,即面向切面编程
AOP(面向切面编程)是一种编程模式

1.2 AOP的作用

  • 在编译期间对代码进行动态管理,达到统一维护的目的。
  • 将某些特定的功能切面织入到类的方法中,以实现对类的行为进行控制和监控。

1.3 AOP 与 AspectJ的关系

AspectJ是AOP的著名实现之一,是SpringAOP的基础。
AspectJ是AOP的一种实现方式,可以通过编写切面来实现AOP。

二、AspectJ 介绍

2.1 AspectJ 的实现原理

AspectJ通过使用注解和XML配置,可以在运行时动态地将代码切入到程序的各个部分,实现面向切面的编程。

2.2 AspectJ 的好处

AspectJ可以对业务逻辑的各个模块进行隔离,降低模块间耦合度,提高程序的可重用性,进而提高开发效率。

2.4 AspectJ 的三种织入方式

AspectJ的织入方式有三种:

  • 编译器织入
  • 类装载期织入
  • 动态代理织入

2.4 简单的AOP AspectJ入门示例:

2.4.1 编写切面

可以在SpringBoot项目中创建一个切面类,用来控制类的行为。
以下是一个简单的切面类示例:

@Aspect
@Component
public class LogAspect {
 
    @Pointcut("execution(* com.example.service.*.*(..))")
    public void serviceMethods() {}
 
    @Before("serviceMethods()")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Before method execution: " + joinPoint.getSignature().getName() + " called");
    }
 
    @AfterReturning("serviceMethods()")
    public void logAfterReturning(JoinPoint joinPoint) {
        System.out.println("After method execution: " + joinPoint.getSignature().getName() + " returned");
    }
 
    @AfterThrowing(pointcut = "serviceMethods()", throwing = "ex")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable ex) {
        System.out.println("After method execution: " + joinPoint.getSignature().getName() + " threw exception: " + ex.getMessage());
    }
 
}

在上述代码中,我们定义了一个LogAspect类来实现AOP。
其中,

  • @Aspect注解表示该类是一个切面类
  • @Pointcut注解定义了切入点,即控制哪些方法需要被切面织入
  • @Before注解表示在方法执行前执行一些操作
  • @AfterReturning注解表示在方法执行后返回时执行一些操作
  • @AfterThrowing注解表示在方法执行出现异常时执行一些操作

2.4.2 配置切面

可以在SpringBoot项目中创建一个配置类,用来配置切面的执行顺序和其他参数。
以下是一个简单的配置类示例:

@Configuration
@EnableAspectJAutoProxy
public class AppConfig {
    
    
    @Bean
    public LogAspect logAspect() {
    
    
        return new LogAspect();
    }
}

在上述代码中,通过

  • @Configuration注解来标记该类是一个配置类;
  • @EnableAspectJAutoProxy注解表示启用Spring的AOP支持;
  • @Bean注解表示创建一个LogAspect对象,并将其注入到Spring容器中。

2.4.3 使用切面

可以在SpringBoot项目中创建一个Service类,并使用切面来控制其行为。
以下是一个简单的Service类示例:

@Service
public class UserServiceImpl implements UserService {
    
    
    @Override
    public void addUser(User user) {
    
    
        System.out.println("User added: " + user.getName());
    }
}

在上述代码中,实现了一个UserService接口,并使用@Service注解来标记该类是一个Service类。

猜你喜欢

转载自blog.csdn.net/wstever/article/details/129926770