[英]Spring not injecting @value annotation in property
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:我正在从控制器调用方法 test():
@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.但是,即使该类具有@Component
注释,spring 也不会注入build.version
值。
I am using the same property in a controller and it works fine.我在控制器中使用相同的属性,它工作正常。
What am I doing wrong?我究竟做错了什么?
If you are using application.yml
to provide value to these properties then use @ConfigurationProperties
on top of the class.如果您使用application.yml
为这些属性提供值,则在类的顶部使用@ConfigurationProperties
。 You do not need to give @Value
on every property value, for example:您不需要为每个属性值提供@Value
,例如:
@Component
@Data
@ConfigurationProperties(prefix = "build")
public class SchedulerProperties {
private String buildVersion;
}
In application.yml
define as below在application.yml
中定义如下
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());
}
}
Try out this way, as you create instance with new instead of rely on Spring object managing(Inversion of control)尝试这种方式,因为您使用 new 创建实例而不是依赖 Spring 对象管理(控制反转)
@RestController
public class ApiController {
private Scheduler scheduler;
@Autowired
public ApiController(Scheduler scheduler) {
this.scheduler = scheduler
}
@GetMapping("/status")
public StatusResponse status() {
scheduler.update();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.