如何解决使用 Spring Boot
我没有在任何地方看到过这样的问题,所以我要在这里问一下。我必须为一种对象类型创建几个实例,应该从文件 .properties 中提供我必须实例化的实例数量。我尝试使用注释@Value 但它总是给我
空指针异常
因为值为空。 所以例如我有
application.properties
在我的资源文件夹中。 假设文件如下所示:
instances.number=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")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。