I am getting null as a value when I use @Value with @AllArgsConstructor combination.
@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");
}
}
}
In the doSomething()
, I am getting threshold
variable value as null
Could you please help me on this.
CodePudding user response:
When you create a constructor, you're telling spring boot container that class dependencies will be injected using it. In that case, dependency specifications like @Qualified
or @Value
need to be declared on constructor parameter. Because your constructor is being generated by lombok, it doesn't includes annotations on parameters.
Using @Value
directly on the field works for field injection, but in your case you are using constructor injection.
For your code to work you'll need to do the following:
@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");
}
}
}
CodePudding user response:
When I used both @NoArgsConstructor and @AllArgsConstructor it worked.
@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");
}
}
}
CodePudding user response:
You can use @RequiredArgsConstructor to inject your beans via constructor and your threshold value to be injected with field injection. For that you have to make your beans final
@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");
}
}
}
CodePudding user response:
You should use @RequiredArgsConstructor
, it will initialize only the fields marked with @NonNull
or final
keyword.