Skip to content

在SpringBoot中使用AOP需要引入以下依赖

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

在SpringBoot中使用AOP是全注解形式,跟spring中相像(具体查看 Spring -> AOP.md)

样例

做一个日志打印输出

切面类

java
@Aspect
@Component // 切面类
public class LogAspect {
    @Before("execution(* top.xmln.newspringboot.service..*.*(..))")
    public void sysLog(JoinPoint jp) {
        // 记录日志
        StringJoiner log = new StringJoiner(" | ", "{", "}");
        // 日期格式化
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 拼接日期
        log.add(formatter.format(java.time.LocalDateTime.now()));
        // 拼接方法
        log.add(jp.getSignature().getName());
        // 获取参数
        Object[] args = jp.getArgs();
        // 拼接参数
        for (Object arg : args) {
            log.add(arg == null ? "-" : arg.toString());
        }
        // 打印输出
        System.out.println("日志:" + log);
    }
}

接口

java
public interface SomeService {
    void query(Integer id);
    void save(User user);
}

被增强类

java
@Service
public class SomeServiceImpl implements SomeService {
    @Override
    public void query(Integer id) {
        System.out.println("查询数据");
    }

    @Override
    public void save(User user) {
        System.out.println("保存数据");
    }
}

execution 表达式格式详解

基本语法结构

java
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)

各位置作用说明

  1. modifiers-pattern - 方法修饰符模式

    • 可选参数
    • 匹配方法的访问修饰符(如 publicprivateprotected
    • 示例:publicprivate
  2. ret-type-pattern - 返回值类型模式

    • 必需参数
    • 匹配方法的返回值类型
    • 使用 * 匹配任意返回类型
    • 示例:voidString*
  3. declaring-type-pattern - 声明类型模式

    • 可选参数
    • 匹配方法所在的类或接口
    • 使用 .. 表示包及其子包
    • 示例:com.example.service.UserService
  4. name-pattern - 方法名模式

    • 必需参数
    • 匹配具体的方法名称
    • 支持通配符匹配
  5. param-pattern - 参数列表模式

    • 必需参数
    • 匹配方法的参数类型和数量
    • .. 表示任意数量和类型的参数
  6. throws-pattern - 异常声明模式

    • 可选参数
    • 匹配方法声明抛出的异常类型
    • 示例:throws Exception

特殊字符说明

  • * - 通配符

    • 匹配任意数量的字符
    • 在类型模式中匹配任意类型
  • .. - 通配符

    • 在包名中:匹配当前包及其所有子包
    • 在参数中:匹配任意数量和类型的参数
  • + - 继承匹配符

    • 匹配指定类及其子类
    • 示例:execution(* com.example.User+.*(..))

常用示例

java
// 匹配所有公共方法
execution(public * *(..))

// 匹配指定包下所有方法
execution(* com.example.service..*.*(..))

// 匹配特定类的所有方法
execution(* com.example.service.UserService.*(..))

// 匹配以save开头的方法
execution(* save*(..))