當我將 @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 你能幫我解決這個問題嗎?
uj5u.com熱心網友回復:
創建建構式時,您是在告訴 spring boot 容器類依賴項將使用它注入。在這種情況下,依賴規范像@Qualified或@Value需要在建構式引數上宣告。因為您的建構式是由 lombok 生成的,所以它不包含引數注釋。
@Value直接在欄位上使用適用于欄位注入,但在您的情況下,您使用的是建構式注入。
要使您的代碼正常作業,您需要執行以下操作:
@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");
}
}
}
uj5u.com熱心網友回復:
您可以使用 @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");
}
}
}
uj5u.com熱心網友回復:
當我同時使用 @NoArgsConstructor 和 @AllArgsConstructor 時,它起作用了。
@Service
@Slf4j
@AllArgsConstructor
@NoArgsConstructor
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");
}
}
}
uj5u.com熱心網友回復:
您應該使用@RequiredArgsConstructor,它只會初始化標有@NonNullorfinal關鍵字的欄位。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344068.html
