繁体   English   中英

使用 Spring Boot 属性中的 int 值

[英]Using int value from properties Spring Boot

我没有在任何地方看到过这样的问题,所以我要在这里问一下。 我必须为一种对象类型创建几个实例,应该从文件 .properties 中提供我必须实例化的实例数量。 我尝试使用注释 @Value 但它总是给我

空指针异常

因为该值为空。 所以例如我有

应用程序属性

在我的资源文件夹中。 假设文件如下所示:

实例数=5 ...

我使用注释:

@Value("${instances.number}")
private static String lastIndex;

我想以这种方式使用它:

psvm {
for(int i = 0; i < Integer.parseInt(lastIndex); i++) {
//creating an instance of object
 }
}

所以我无法解析它,因为它是空值。 我应该怎么做才能正确获取instance.number 值?

...

这可能是因为 Spring 不支持static字段上的 @Value。

也许尝试这样的事情:

@Component
public class PropertyClass {

    @Value("${lastIndex}")
    private integer lastIndex;

    private static Integer LAST_INDEX;

    @Value("${lastIndex}")
    public void setLastIndex(Integer lastIndex){
        PropertyClass.LAST_INDEX = lastIndex;
    }
}

资源: https : //www.baeldung.com/spring-inject-static-field

您可以删除静态并尝试

@Value("${instances.number}")
private String lastIndex;

如果你想通过 @Value 获取值,你应该至少注释类 @Component 然后它会在运行时分配值。

@Service
Public class Config{
@Autowried
 Environment env:

@Value("${instances.number}")
private String lastIndex;

public void test(){
 
System.out.println(env.getProperty("key"));
System.out.println(lastIndex)
}

如果您想避免上述问题,您可以使用

environment.getProperty("keyName")

暂无
暂无

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

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