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

Spring AOP自定义注解在@Component类中不生效问题排查

问题根因
  • 核心原因:你在MGRuleConfig的mRules() Bean创建方法中手动new了SSRule等规则类实例,而非使用Spring容器中已经完成代理增强的实例。即使SSRule类上加了@Component注解,手动创建的对象不归Spring生命周期管理,不会被AOP切面增强,自然无法触发@IPException对应的切面逻辑。
  • 次要问题1:切面方法返回值错误,当前代码返回ProceedingJoinPoint对象而非目标方法的执行结果,会导致后续业务逻辑执行异常。
  • 次要问题2:切点表达式写死仅匹配SSRule类的apply方法,其余规则类即使加了@IPException注解也无法触发切面。
  • 额外检查项:需确认项目是否开启了AOP自动代理,即启动类/配置类上是否添加了@EnableAspectJAutoProxy注解。
解决方案

1. 修正规则Bean的创建逻辑

修改MGRuleConfig类,注入Spring容器中已代理的规则类实例,不要手动new:

@Configuration
@AllArgsConstructor
public class MGRuleConfig {
    private final GRepository repository;
    private final GInitializer initializer;
    private final GMapper mapper;
    // 注入Spring容器中已经完成AOP代理的规则实例
    private final SSRule ssRule;
    private final CSRule csRule;
    private final MPRule mpRule;
    private final EGRule egRule;

    @Bean
    @Qualifier("mRules")
    public List<GRules> mRules(){
        // 直接使用容器托管的代理实例
        return List.of(ssRule, csRule, mpRule, egRule);
    }
    @Bean
    public GService gService() {
        return new MGServiceImpl(repository, initializer, mapper);
    }
}

2. 修正切面逻辑与切点表达式

优化切点匹配范围,同时修正返回值:

@Aspect
@Component
public class IPExceptionAspect {
    // 切点匹配所有GaRules实现类的apply方法,且方法上标注了@IPException注解
    @Around("execution(public * c.m.s.r.GaRules+.apply(..)) && @annotation(c.m.s.i.a.IPException)")
    public Object checkIP(ProceedingJoinPoint pjp) throws Throwable {
        // 此处可添加你需要的异常捕获、IP校验等逻辑
        return pjp.proceed();
    }
}

3. 开启AOP代理(如未配置)

在项目启动类或者配置类上添加@EnableAspectJAutoProxy注解,开启Spring AOP的自动代理能力。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:01