Java AspectJ、SpringAOP、Aspect运行两次

Java AspectJ、SpringAOP、Aspect运行两次,java,spring,aspectj,spring-aop,Java,Spring,Aspectj,Spring Aop,我的相位运行了两次,我看不出原因。也许有人能指出我的错误? 下面是一个代码: 为切入点创建注释 @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface CustodianMetrics { String metricId(); } 创建方面 @Aspect @Component("custodianMetricsAspect") public class Custodian

我的相位运行了两次,我看不出原因。也许有人能指出我的错误? 下面是一个代码:

  • 为切入点创建注释

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ElementType.METHOD})
    public @interface CustodianMetrics {
        String metricId();
    }
    
  • 创建方面

    @Aspect
    @Component("custodianMetricsAspect")
    public class CustodianMetricsAspect {
        private final MonitoringService monitoringService;
    
        @Autowired
        public CustodianMetricsAspect(MonitoringService monitoringService) {
            this.monitoringService = monitoringService;
        }
    
        @After("@annotation(custodianMetricsAnnotation)")
        public void count(CustodianMetrics custodianMetricsAnnotation) {
            Counter metric = monitoringService.metric(custodianMetricsAnnotation.metricId(), Counter.class);
            metric.inc();
        }
    }
    
  • 为spring配置xml

    <aop:aspectj-autoproxy>
        <aop:include name="path"/>
    </aop:aspectj-autoproxy>
    <aop:config>
        <aop:aspect id="custodianMetricsAspect" ref="custodianMetricsAspect">
            <aop:after method="count" 
                     pointcut="@annotation(custodianMetricsAnnotation)"/>
        </aop:aspect>
    </aop:config>
    

    但是相同的结果方面运行了两次。有什么建议吗?

    之所以出现这种情况,是因为您已经两次配置了aspect——Spring XML配置和
    @aspect
    注释

    请阅读Spring框架文档部分中的注释,其中说明了以下内容:

    与本章相关的一个选择是选择哪种AOP框架(以及哪种AOP样式)。您可以选择AspectJ和/或SpringAOP,还可以选择@AspectJ注释样式方法或SpringXML配置样式方法

    在这种情况下,根据我的个人经验,我强烈建议您坚持使用注释。然而,这取决于你的个人品味。你可能会发现相关的

    编辑: 如果选择基于注释的配置,不要忘记创建Java配置类,而不是删除

    @Configuration
    @EnableAspectJAutoProxy
    public class AspectJAutoProxyConfiguration { }
    

    作为一个可能不相关的建议,您应该将切入点限制在包级别,即执行(public*org.mypackage..*(..)。如果对
    @component
    方面的组件扫描处于活动状态,@Nikolas的回答可能是正确的。但是,为了确保它确实是两次触发的同一个joinpoint,而不是另一个类被意外拦截,因为它也具有相同的注释,您可以将
    joinpoint thisJoinPoint
    作为第一个参数添加到
    count()
    建议中,然后像
    System.out.println一样将其打印到控制台(thisJoinPoint)
    。那么你真的知道了。
    我使用这个配置方面根本没有运行。你需要一个Java配置(空)类,用
    @configuration
    @enableSpectjautoproxy
    注释。
    @Configuration
    @EnableAspectJAutoProxy
    public class AspectJAutoProxyConfiguration { }