无法通过ProceedingJoinPoint检索注释

时间:2014-11-06 05:26:39

标签: annotations aop aspectj spring-aop

我想从AOP连接点检索注释。我可以通过反射获得注释,但无法使用ProceedingJoinPoint执行此操作。

如果该方法未使用Profile进行注释,则不会调用该建议...但在建议中,它无法找到注释。

通过ProceedingJoinPoint

@Around("@annotation(com.annotation.Profile)")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Signature signature = joinPoint.getSignature();
    String methodName = signature.toString();
    Method method = ((MethodSignature) signature).getMethod();

    Profile profile = method.getAnnotation(Profile.class);

    // profile is null here...
    // ......

}   

直接反思

public static void main(String[] args) throws NoSuchMethodException, SecurityException {
    Method method = SampleServiceImpl.class.getMethod("getTicket", String.class);
    System.out.println(method.getClass().toString());
    System.out.println(method.getAnnotation(Profile.class));
}

我的注释

@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Profile {
    public long skipCount();
    public long sampleSize();
}

我的带注释的方法

@Override
@Cacheable("test")
@Transactional
@Profile(skipCount = 100, sampleSize = 100)
public Tickets getTicket(String ticketId) {
    return sampleDao.getTicket(ticketId);
}

我的POM

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <jdk.version>1.8</jdk.version>
    <spring.version>4.1.1.RELEASE</spring.version>
    <aspectj.version>1.8.3</aspectj.version>
</properties>

<!-- Spring AOP + AspectJ -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>${aspectj.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
        </dependency>

1 个答案:

答案 0 :(得分:2)

不需要反思,这更容易。您可以将注释绑定到advice参数:

@Around("@annotation(profileAnnotation)")
public Object logAround(Profile profileAnnotation, ProceedingJoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint + " - " +  profileAnnotation);
    // (...)
    Object result = thisJoinPoint.proceed();
    // (...)
    return result;
}

控制台输出可能是这样的:

execution(void de.scrum_master.app.Application.main(String[])) - @de.scrum_master.app.Profile(skipCount=5, sampleSize=11)