【问题标题】:Can we disable AOP invocations?我们可以禁用 AOP 调用吗?
【发布时间】:2026-02-22 05:20:14
【问题描述】:

我有以下设置的基于 AOP 的登录功能

上下文xml配置:

<bean id="performanceMonitor" 
class="org.springframework.aop.interceptor.PerformanceMonitorInterceptor" />

<aop:config>
        <aop:pointcut id="allServiceMethods" 
            expression="execution(* com.eshop.sfweb.service.impl..*(..))" /> 
    <aop:pointcut id="allEpServices" 
            expression="execution(* com.service.catalog..*(..))" />
        <aop:advisor pointcut-ref="allServiceMethods" 
            advice-ref="performanceMonitor" order="2" /> 
        <aop:advisor pointcut-ref="allEpServices"
            advice-ref="performanceMonitor" order="2" />
    </aop:config>

Log4j 属性:

log4j.logger.org.springframework.aop.interceptor.PerformanceMonitorIntercept
or=${ep.perflog.level},PERFORMANCE 
log4j.appender.PERFORMANCE.File=webAppRoot:WEB-INF/log/performance.log 
log4j.appender.PERFORMANCE.threshold=DEBUG 
log4j.appender.PERFORMANCE=org.apache.log4j.DailyRollingFileAppender 
log4j.appender.PERFORMANCE.DatePattern='.'yyyy-MM-dd 
log4j.appender.PERFORMANCE.layout=org.apache.log4j.PatternLayout 
log4j.appender.PERFORMANCE.layout.ConversionPattern=%d -- %-5p [%t | %F:%L] 
-- %m%n

有什么方法可以根据环境禁用 AOP 调用本身? 我可以很容易地禁用日志记录,但我可以禁用/启用整个后台进程和调用吗?

如果需要任何澄清,请告知。

【问题讨论】:

    标签: java log4j aop aspectj spring-aop


    【解决方案1】:

    由于您使用的是 Spring AOP,因此启用或禁用方面的一种快速方法可能是简单地使用 Bean 配置文件。

    定义一个配置文件说enableAOP: 将 aop:config 包装在特定配置文件下的配置文件中

    <beans profile="enableAOP">
        <aop:config> <aop:pointcut id="allServiceMethods" 
        expression="execution(* com.eshop.sfweb.service.impl..*(..))" /> 
        <aop:pointcut id="allEpServices" expression="execution(* 
        com.service.catalog..*(..))" />
    ....
    </beans>
    

    现在,无论您希望启用特定方面的哪个环境,只需打开enableAOP 配置文件即可运行。

    【讨论】:

    • 请问哪个版本的spring支持bean的这个profile属性?我在 spring 2.0 中尝试过,但无法解析 spring bean xml。
    • 优秀的答案。简洁、优雅、精确。
    【解决方案2】:

    这个问题被问到已经有一段时间了,但这是我为 Spring 2 想出的:

    使用空的 &lt;beans&gt; 声明创建一个空的 xml 文件 (aop-context-off.xml)。 然后使用您的 AOP 声明创建一个 aop-context-enabled.xml 文件。

    最后在导入 XML 时可以使用:

    <import resource="aop-context-${AOP_CONTEXT_SUFFIX:off}.xml" />
    

    这将查找名为 AOP_CONTEXT_SUFFIX 的系统变量,如果未找到,则将该值强制为 off

    所以在上面的例子中,通过将AOP_CONTEXT_SUFFIX 设置为enabled 它将加载aop-context-enabled.xml

    所以开关是系统变量,你可以在服务器启动时轻松启用/禁用它。

    【讨论】:

      最近更新 更多