Spring AOP获取注释值

时间:2017-01-14 21:58:35

标签: aop spring-aop spring-annotations

我正在使用spring AOP,如何从注释中获取值, 这是我的注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
@Documented
public @interface ExecutionMethodProfiler 
{
    String value() default "defaultValue";;
}

这是我的XML:

<aop:aspectj-autoproxy/>
    <aop:config>
        <aop:aspect ref="methodProfiler">
            <aop:pointcut id="serviceMethod" 
                expression="(execution(* com.old..*(..)) or execution(* com.test..*(..))) and @annotation(com.test.profiler.ExecutionMethodProfiler)" />
            <aop:around pointcut-ref="serviceMethod" method="profile"/>
        </aop:aspect>
    </aop:config>

这是我的serviceMethod:

public void profile(ProceedingJoinPoint jointPoint) throws Throwable {}

截至目前,我可以使用此代码获取值:

MethodSignature signature = (MethodSignature) jointPoint.getSignature();
System.out.println(signature.getMethod().getAnnotation(ExecutionMethodProfiler.class).value());

我不喜欢它,有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

首先更改您的建议,将您的注释作为附加参数:

public void profile(
    ProceedingJoinPoint jointPoint,
    ExecutionMethodProfiler methodProfiler
) throws Throwable {}

然后将注释绑定到切入点中的该参数:

<aop:around
    pointcut="(execution(* com.old..*(..)) or execution(* com.test..*(..))) and @annotation(methodProfiler)"
    method="profile"
    arg-names="methodProfiler"
/>

我实际上并没有对它进行测试,因为我现在有点忙,但这基本上就是它的工作方式。

相关问题