java - 当我在枚举中使用属性值时出现 Spring Boot 错误
问题描述
我有一个 Spring Boot 项目,我正在尝试恢复 .properties 文件的值并在枚举中使用它。
我遵循接下来的步骤。
我有一个
application.properties
带有value = 000
. 我通过以下方式恢复此值:@RestController public class ReadProperty { @Value("${value}") public String value; public String getValueProperty() { return this.value; } @GetMapping(value = "/get") public String getValue() { System.out.println("read value is " + value); return value; } @GetMapping(value = "/getEnum") public String getValueEnum() { String response = EnumInsideAClass.TEST.toString(); System.out.println("response value is " + response); return response; } }
如果我在类中使用值,我会毫无问题地得到值 000。
我在这样的类中创建了一个枚举
public class EnumTest { @Autowired static ReadProperty readProperty; public final static String VAL = readProperty.getValueProperty(); public enum EnumInsideAClass { TEST(VAL); private String value; private EnumInsideAClass(String value) { this.value = value; } @Override public String toString() { return this.value; } } }
问题是在枚举类内部我需要一个静态变量。如果我使用
@Value("${value}")
public static String value;
值更改为 null。
所以我尝试通过 get 方法访问该值,但该值仍然为空。
我没有想法,我该怎么办?可以在枚举中使用属性值吗?
非常感谢
解决方案
The problem you're describing has nothing to do with the @Value
being in the enum
but rather it has to do with your attempt to inject the property's value on a static variable.
Spring will let you inject values directly on non-static and not on static fields. If you want to do this in your case, you could potentially proxy the injection through a setter method e.g:
public static String value;
@Value("${value}")
public void setValue(String someValue) {
SomeClass.value = someValue;
}
But I would advise you to be very aware of what you're doing. Since this is going to be a non-final field that is also public and static you need to be aware of who's allowed to access it and also who's allowed to change it's value.
推荐阅读
- html - 在表格单元格内的两个图像之间放置一个 Div
- android - 如果在viewmodel中做简单的操作,我们需要livedata吗
- java - 如何从数组中删除重复元素
- javascript - jQuery函数在第一次点击后停止工作
- java - Spring JPA Hibernate 自动填充审计字段(创建 ID/时间戳等)
- c# - Acumatica - 获取附加文件计数的语法是什么?
- c - 获取使用 GNU 自动工具编译的项目的所有包含列表
- yarnpkg - 得到 gyp 错误
- ios - 如何创建一个将弱自我传递到闭包内部的闭包签名
- java - 如何有条件地执行 Reactor 的 Mono/Flux 供应商算子?