Search code examples
spring-aopspring-annotations

Spring AOP only method with annotation


I have this AOP that run on all my application methods, but I want it to run only on methods that annotation with ProfileExecution annotation, how can I do it using this xml

<bean id="profiler" class="com.mytest.ProfilerExecution" />


<aop:config>
    <aop:aspect ref="profiler">

        <aop:pointcut id="serviceMethod" 
            expression="execution(public * *(..))" />
            <aop:around pointcut-ref="serviceMethod" method="profile"/>
    </aop:aspect>
</aop:config>

Thanks


Solution

  • Use following pointcut expression @annotation(com.abc.xyz.ProfileExecution) with AND operation to filter the methods.

    So final xml should look like below

    <aop:config>
        <aop:aspect ref="profiler">
            <aop:pointcut id="serviceMethod" 
                expression="execution(public * *(..)) and @annotation(com.abc.xyz.ProfileExecution)" />
            <aop:around pointcut-ref="serviceMethod" method="profile"/>
        </aop:aspect>
    </aop:config>
    

    Make sure to include the fully qualified name of annotation in the expression else it won't work.