Issue
I have the following class:
@Component
public class Scheduler {
@Value("${build.version}")
private String buildVersion;
public void test() {
System.out.println(this.buildVersion);
}
}
I am calling the method test() from a controller:
@RestController
public class ApiController {
@GetMapping("/status")
public StatusResponse status() {
Scheduler scheduler = new Scheduler();
scheduler.update();
}
However spring is not injecting the build.version
value even though the class has a @Component
annotation.
I am using the same property in a controller and it works fine.
What am I doing wrong?
Solution
Try out this way, as you create instance with new instead of rely on Spring object managing(Inversion of control)
@RestController
public class ApiController {
private Scheduler scheduler;
@Autowired
public ApiController(Scheduler scheduler) {
this.scheduler = scheduler
}
@GetMapping("/status")
public StatusResponse status() {
scheduler.update();
}
}
Answered By - Tsvetoslav Tsvetkov
Answer Checked By - Gilberto Lyons (JavaFixing Admin)