【问题标题】:Using int value from properties Spring Boot使用属性 Spring Boot 中的 int 值
【发布时间】:2021-09-19 15:58:03
【问题描述】:

我没有在任何地方看到这样的问题,所以我要在这里问一下。我必须为一种对象类型创建几个实例,我必须实例化的实例数应该从文件 .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 值?

...

【问题讨论】:

  • 就像@Autowired 一样,使用@Value 注入值仅适用于Spring bean。如果你的类不是 Spring bean,那么这些注释什么都不做,你的字段将保持 null

标签: java spring-boot properties-file


【解决方案1】:

你可以删除静态试试

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

【讨论】:

    【解决方案2】:

    这可能是因为 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

    【讨论】:

    • 我尝试以非静态方式使用它,它仍然为空。
    • @TadeuszM,确保您尝试从属性文件中注入值的类是 Spring Bean。
    【解决方案3】:

    如果你想通过@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")
    

    【讨论】:

    • 在这两种情况下我仍然有 null。
    猜你喜欢
    • 2021-01-16
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2020-07-13
    • 1970-01-01
    • 2016-08-10
    • 2018-03-01
    • 2016-04-16
    相关资源
    最近更新 更多