You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring AOP父子类关系下切点表达式失效,请求审计通知无法触发求助

Spring AOP父子类(接口实现)场景下切点不触发的解决方案

问题根源

你的切点表达式@annotation(...)只会匹配方法自身直接标注的注解,但子类Child重写的createJsonSchemaMetadata方法没有显式添加@GetMapping注解——该注解定义在父接口Parent的方法上,而Java方法注解默认不会被继承,因此Spring AOP无法匹配到目标方法,导致通知不触发。

解决方案

方案1:在子类重写方法上显式添加注解

这是最简单直接的方式,直接在子类实现的方法上复制接口方法的注解:

@RestController
@Validated
@RequestMapping("/api")
public class Child implements Parent {

    @Override
    @GetMapping(value = "/test") // 显式添加接口方法的注解
    public ResponseEntity<?> createJsonSchemaMetadata() {
        return ResponseEntity.status(HttpStatus.OK).body("Successful");
    }
}

修改后,原来的切点表达式就能正常匹配到该方法,触发审计通知。

方案2:修改切点表达式,匹配接口方法上的注解

如果不想修改大量子类代码,可以调整切点表达式,使其同时匹配方法自身注解和接口方法上的注解:
修改PointcutDefinition类的切点定义:

@Aspect
public class PointcutDefinition {

    // 匹配方法自身或接口方法上的GET/POST/PUT/DELETE注解
    @Pointcut(
        // 匹配方法自身直接标注的HTTP注解
        "(execution(* *(..)) && (@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.DeleteMapping))) || " +
        // 匹配接口中带有HTTP注解的方法(以Parent接口为例,可替换为更通用的接口范围)
        "(execution(* *..Parent+.*(..)) && (@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.PutMapping) || " +
        "@annotation(org.springframework.web.bind.annotation.DeleteMapping)))"
    )
    public void httpMethodsWithAnnotation() {
    }

    // 同样修改RequestMapping的切点,匹配方法自身或接口方法上的@RequestMapping
    @Pointcut(
        "(execution(* *(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)) || " +
        "execution(* *..Parent+.*(..)) && @annotation(org.springframework.web.bind.annotation.RequestMapping)"
    )
    public void requestMappingMethodsWithHttpMethods() {
    }

}

其中Parent+表示Parent接口及其所有实现类,这样就能匹配到子类实现的接口方法。如果需要匹配所有接口的方法,可以把Parent+替换为更通用的范围,但注意不要过度扩大匹配范围。

验证

修改完成后,启动项目访问/api/test,控制台应该会输出Auditing triggered.,说明通知已成功触发。

内容的提问来源于stack exchange,提问作者Prajyod Kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:15:03