首页 > 解决方案 > 使用 @AllArgsConstructor 获取 @Value 的空值

问题描述

当我将 @Value 与 @AllArgsConstructor 组合使用时,我得到 null 作为值。

@Service
@Slf4j
@AllArgsConstructor
public class ReconService{
    
    private ReconRepo reconRepo;
    private InService inService;
    @Value("${threshold.count}")
    private Integer threshold;
    
    public void doSomething(List<Record> records) {
       if(threshold < records.size()) {
         throw new RuntimeException("threshold exceeded");
       }
    }
}

在中doSomething(),我将threshold变量值设为 null 你能帮我解决这个问题吗?

标签: javaspring-boot

解决方案


您可以使用@RequiredArgsConstructor 通过构造函数注入您的bean,并使用字段注入注入您的阈值。为此,您必须使您的豆子最终化

@Service
@Slf4j
@RequiredArgsConstructor
public class ReconService{
    
    private final ReconRepo reconRepo;
    private final InService inService;
    @Value("${threshold.count}")
    private Integer threshold;
    
    public void doSomething(List<Record> records) {
       if(threshold < records.size()) {
         throw new RuntimeException("threshold exceeded");
       }
    }
}



推荐阅读