首页 > 解决方案 > 当我在枚举中使用属性值时出现 Spring Boot 错误

问题描述

我有一个 Spring Boot 项目,我正在尝试恢复 .properties 文件的值并在枚举中使用它。

我遵循接下来的步骤。

如果我在类中使用值,我会毫无问题地得到值 000。

问题是在枚举类内部我需要一个静态变量。如果我使用

@Value("${value}")
public static String value;

值更改为 null。

所以我尝试通过 get 方法访问该值,但该值仍然为空。

我没有想法,我该怎么办?可以在枚举中使用属性值吗?

非常感谢

标签: javaspring-bootenumsproperties

解决方案


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.


推荐阅读