【发布时间】: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