使用@Value搭配@AllArgsConstructor时注入属性为null问题求助
问题根本原因
Spring实例化Bean时,若类上标注了Lombok的@AllArgsConstructor,会优先使用生成的全公共构造函数完成依赖注入。此时Lombok自动生成的构造函数中,threshold参数没有携带@Value注解,Spring无法识别该参数需要从配置文件中读取值,只会按常规Bean注入逻辑查找Integer类型的Bean,找不到就会传入null,且后续不会再处理字段上标注的@Value注解,最终导致threshold字段为null。
可行解决方案
- 方案1:改用
@RequiredArgsConstructor注入Bean依赖,保留字段上的@Value注解
将需要注入的Bean类型字段标记为final,threshold不做final修饰,@RequiredArgsConstructor只会为final字段生成构造函数,Spring会在实例化完成后单独处理字段上的@Value注入。
@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"); } } }
- 方案2:手动编写构造函数,在构造参数上添加
@Value注解
放弃Lombok自动生成的全参构造,手动定义构造函数,将@Value注解放到构造函数的threshold参数上,Spring会自动从配置中读取值注入到构造参数中。
@Service @Slf4j public class ReconService{ private ReconRepo reconRepo; private InService inService; private Integer threshold; // 手动编写构造函数 public ReconService(ReconRepo reconRepo, InService inService, @Value("${threshold.count}") Integer threshold) { this.reconRepo = reconRepo; this.inService = inService; this.threshold = threshold; } public void doSomething(List<Record> records) { if(threshold < records.size()) { throw new RuntimeException("threshold exceeded"); } } }
- 方案3:使用
@ConfigurationProperties绑定配置类
将配置项统一绑定到独立的配置类中,再将配置类作为Bean注入到ReconService中,可完全避免@Value和构造函数注解的冲突问题。
内容的提问来源于stack exchange,提问作者Ram
相关产品推荐
相关产品推荐

