我正在尝试将日志记录添加到我的界面默认方法中。例如:
@Slf4j // not allowed
interface MyIFace {
default ThickAndThin doThisAndThat() {
log.error("default doThisAndThat() called");
}
}
问题是我得到:
@Slf4j 仅在类和枚举上合法。
处理这个问题的正确方法是什么?
这里不能使用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");
}
}
使用 Java 9+,您可以使用私有方法来防止记录器成为公共静态
public interface MyIFace {
private Logger log() {
return LoggerFactory.getLogger(MyIFace.class);
}
default void doThisAndThat() {
log().error("default doThisAndThat() called");
}
}