Home > Software design >  Cannot get value from application.yml in static method
Cannot get value from application.yml in static method

Time:12-20

I cannot get value from application.yml in static method. However I could get the same value in my Controller. So, I think trying to reach that value from a static method. So, how can I fix it? I also tried to use constructor and set codeSize value, but still 0. Any idea?

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

CodePudding user response:

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

CodePudding user response:

You are using Spring. The default scope is Singleton. So you anyway have only one instance of the bean.

Therefor you shouldn't use static at all in Spring beans.

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