【问题标题】:Spring AspectJ Custom Annotation for Logging用于日志记录的 Spring AspectJ 自定义注释
【发布时间】:2015-08-18 15:11:15
【问题描述】:

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

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() 则会触发)。

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

【问题讨论】:

    标签: spring aspectj spring-annotations


    【解决方案1】:

    不,这是不可能的(还没有?)。

    注解只能在类之间继承,即使这样也只能在它们本身使用元注解@Inherited进行注解时:

    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 注释在用于注释类型以外的任何内容时不会被继承。实现一个或多个接口的类型永远不会从它实现的接口继承任何注释。

    【讨论】:

    • 谢谢,我已在方法实现级别添加注释以使其正常工作。
    猜你喜欢
    • 2013-11-01
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多