【问题标题】:Cannot get value from application.yml in static method无法在静态方法中从 application.yml 获取值
【发布时间】:2022-01-20 11:03:58
【问题描述】:

我无法在静态方法中从 application.yml 获取价值。但是我可以在我的控制器中获得相同的值。因此,我认为尝试通过静态方法达到该值。那么,我该如何解决呢?我还尝试使用构造函数并设置codeSize 值,但仍然为0。有什么想法吗?

@Component
@RequiredArgsConstructor
public class QRCodeGenerator {

    @Value("${qr-code.codeSize}")
    private static int codeSize;

    public static byte[] getQRCode(String data) throws IOException {

        // here codeSize value is 0 instead of 300 that I set in application.yml
        BitMatrix byteMatrix = qrCodeWriter.encode(codeSize, ...);

        // code omitted
    }
}

【问题讨论】:

  • 你不能对静态字段使用依赖注入。
  • @SimonMartinelli 你有什么建议?如果我从我的控制器获得qr-code.codeSize 并从那里(控制器)将它传递给getQRCode 方法呢?即使需要多使用一个参数,这是否是一种更好的方法?
  • 我不明白为什么它必须是静态的。 QRCodeGenerator 无论如何都是单例
  • 其实我也不是很确定,但是我认为它是一个 Util 方法,可能不需要创建该类的新实例。但如果您有其他建议,我当然可以评估。
  • 是的,如果你想使用 Spring,请确保删除所有静态内容

标签: java spring-boot dependency-injection static yaml


【解决方案1】:

您正在使用 Spring。默认范围是单例。所以无论如何你只有一个 bean 实例。

因此,您根本不应该在 Spring bean 中使用静态。

@Component
@RequiredArgsConstructor
public class QRCodeGenerator {

    @Value("${qr-code.codeSize}")
    private final int codeSize;

    public byte[] getQRCode(String data) throws IOException {

        // here codeSize value is 0 instead of 300 that I set in application.yml
        BitMatrix byteMatrix = qrCodeWriter.encode(codeSize, ...);

        // code omitted
    }
}

【讨论】:

  • 非常感谢 Amigo。然后,在 Spring 中,我尽可能地避免使用静态,并为这类东西创建一个服务。问候。
【解决方案2】:

我不会推荐它,并且可能会重新设计您的应用程序结构,但如果您绝对确定您想要在 @Component 中使用静态方法并且您需要访问属性值,那么您可以使用以下解决方法:

@Component
@RequiredArgsConstructor
public class QRCodeGenerator {
         
    private static int codeSize;

    @Value("${qr-code.codeSize}")
    public void setCodeSize(int codeSize){
       QRCodeGenerator.codeSize = codeSize;
    }

    public static byte[] getQRCode(String data) throws IOException {

        // here codeSize value is 0 instead of 300 that I set in application.yml
        BitMatrix byteMatrix = qrCodeWriter.encode(codeSize, ...);

        // code omitted
    }
}

【讨论】:

  • 非常感谢您的回复。我想要一个静态方法,但是如果您不推荐您在上面发布的这种方法,那么如果我从我的 Controller 获取 qr-code.codeSize 并将它从那里(Controller)传递给 getQRCode 方法呢?即使需要使用更多参数,它是否是一种更好的方法?
  • 嗯,如果它从不改变,老实说,我看不出将它作为参数传递的意义。你能详细说明为什么你需要一个静态方法吗? :)
  • 其实我也不是很确定,但我认为它是一个 Util 方法,可能不需要创建该类的新实例。但如果您有其他建议,我当然可以评估。
  • 在不知道您的代码库的情况下很难说,而且这可能超出了这个问题的范围 :) 我只能说我总是试图依赖我的类作为 Spring 组件/服务。在 Util 类中,我永远不会尝试调用组件,它应该是相反的。
  • 另一方面,我在尝试时添加了@Component 注释,可能不需要它。假设您需要一个二维码生成器类。那么你将在哪里实施它以及如何实施?据我所知,没有必要为此使用服务。有什么想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多