简体   繁体   English

无法从 static 方法中的 application.yml 获取值

[英]Cannot get value from application.yml in static method

I cannot get value from application.yml in static method.我无法从 static 方法中的application.yml获得价值。 However I could get the same value in my Controller.但是我可以在我的 Controller 中获得相同的值。 So, I think trying to reach that value from a static method.因此,我认为尝试通过 static 方法达到该值。 So, how can I fix it?那么,我该如何解决呢? I also tried to use constructor and set codeSize value, but still 0. Any idea?我也尝试使用构造函数并设置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
    }
}

I would not recommend it and would probably redesign your app structure, but if you're absolutely sure that you want a static method in your @Component and where you need to access the property value, here's a workaround you could use:我不会推荐它,并且可能会重新设计您的应用程序结构,但是如果您绝对确定要在@Component中使用 static 方法并且您需要访问属性值,那么您可以使用以下解决方法:

@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
    }
}

You are using Spring.您正在使用 Spring。 The default scope is Singleton.默认的 scope 是 Singleton。 So you anyway have only one instance of the bean.所以无论如何你只有一个bean的实例。

Therefor you shouldn't use static at all in Spring beans.因此,您根本不应该在 Spring bean 中使用 static。

@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
    }
}

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

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