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?
CodePudding user response:
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();
}
}
CodePudding user response:
If you are using application.yml
to provide value to these properties then use @ConfigurationProperties
on top of the class. You do not need to give @Value on every property value, for example:
@Component
@Data
@ConfigurationProperties(prefix = "build")
public class SchedulerProperties {
private String buildVersion;
}
In application yml define as below
build:
buildVersion: "XYZ"
Then you can just call version from the properties class
@Component
public class Scheduler {
@Autowired
private SchedulerProperties schedulerProperties;
public void test() {
System.out.println(schedulerProperties.getBuildVersion());
}
}