简体   繁体   English

lombok 日志注释不适用于 static 方法

[英]lombok log annotation is not working for static methods

I am trying to use lombok's @Slf4j annotation.我正在尝试使用 lombok 的 @Slf4j 注释。 It works fine for non-static methods but I am unable to use them for static ones, eg:它适用于非静态方法,但我无法将它们用于 static 方法,例如:

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyClass {

    public static void staticMethod() {
        log.info(""); //build error
        //code
    }

    public void nonStaticMethod() {
        log.info(""); //builds ok
        //code
    }

More specifically the build error is:更具体地说,构建错误是:

Error:(17, 9) java: non-static variable log cannot be referenced from a static context

So either I am missing something or this simply is not the way to do it, but what is causing me some confusion is that other answers seem to indicate that this usage is the correct one.所以要么我遗漏了一些东西,要么这根本不是这样做的方法,但让我有些困惑的是,其他答案似乎表明这种用法是正确的。 Does anyone know what am I doing wrong?有谁知道我做错了什么? Thank you for your help.谢谢您的帮助。

Check with Delombok what exactly does lombok generate in your case.与 Delombok 核实在您的情况下 lombok 究竟会生成什么。

Usually the logger should be a static field.通常记录器应该是一个 static 字段。

However there is a configuration:但是有一个配置:

lombok.log.fieldIsStatic = [true | false] (default: true)

From the documentation: Normally the generated logger is a static field.从文档中:通常生成的记录器是 static 字段。 By setting this key to false, the generated field will be an instance field instead.通过将此键设置为 false,生成的字段将改为实例字段。

Of course if the field is non-static you can't use it from the static method as usual in java当然,如果该字段是非静态的,则不能像往常一样在 java 中从 static 方法中使用它

A link to documentation文档链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM