Lombok @Slf4j 和接口?

问题描述 投票:0回答:2

我正在尝试将日志记录添加到我的界面默认方法中。例如:

@Slf4j // not allowed
interface MyIFace {
    default ThickAndThin doThisAndThat() {
        log.error("default doThisAndThat() called"); 
    }
}

问题是我得到:

@Slf4j 仅在类和枚举上合法。

处理这个问题的正确方法是什么?

java logging slf4j lombok default-method
2个回答
24
投票

这里不能使用Lombok,因为注释会生成:


private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(YourClass.class);

您不能在接口中使用 private 关键字。

解决方法是直接写


interface MyIFace {

   org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(MyIFace.class);

   default ThickAndThin doThisAndThat() {
     log.error("default doThisAndThat() called"); 
   }

}



0
投票

使用 Java 9+,您可以使用私有方法来防止记录器成为公共静态

public interface MyIFace {
    private Logger log() {
        return LoggerFactory.getLogger(MyIFace.class);
    }

    default void doThisAndThat() {
        log().error("default doThisAndThat() called");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.