用于记录的Spring AspectJ自定义注释

时间:2015-08-18 15:11:16

标签: spring aspectj spring-annotations

我已经定义了一个自定义注释,如下所示。

package com.xyz;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Loggable {
    String message() default "Log Message";
}

我的方面类包含以下方法:

@Around(value = "@annotation(com.xyz.Loggable)")
public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    // come code here
}

我的服务界面如下。

public interface Service {
   @Loggable
   public void method1();
}

我的实施如下。

public class ServiceImpl implements Service {
     public void method1() {
         // some code here
     }
}

通过此设置,我的建议不会被触发。 (但是如果我将@Loggable注释移动到ServiceImpl类中的method1(),它会被触发。)

我想保留在接口级而不是方法实现中定义的注释。有没有办法让这项工作?

1 个答案:

答案 0 :(得分:0)

不,那是不可能的(但是?)。

注释只能在类之间继承,即使它们本身也使用元注释2015-08-26T12:02:27.183Z 2015-08-26T14:02:27.183+02:00 进行注释:

http://docs.oracle.com/javase/8/docs/api/java/lang/annotation/Inherited.html

不可能将接口上的注释继承到它们的实现类。

AspectJ文档中也对此进行了解释:http://www.eclipse.org/aspectj/doc/released/adk15notebook/annotations.html#annotation-inheritance

  

当用于注释除类型之外的任何内容时,不会继承@Inherited注释。实现一个或多个接口的类型永远不会从它实现的接口继承任何注释。