[英]SpringBoot does not resolve @Value properties without PropertySource annotation
I have a bunch of @Value
annotated fields in a SpringBoot configuration file, with the matching values in the standard application.properties .我在 SpringBoot 配置文件中有一堆@Value
注释字段,在标准 application.properties 中有匹配的值。 If I don't annotate the configuration file with @PropertySource("classpath:application.properties")
it will just copy the "${prop1}" string into the actual variable.如果我不with @PropertySource("classpath:application.properties")
注释配置文件with @PropertySource("classpath:application.properties")
它只会将“${prop1}”字符串复制到实际变量中。
I tried adding @EnableAutoConfiguration
to the @Configuration class (instead of the PropertySource annotation), but all it does is to break when a requested property is not found.我尝试将@EnableAutoConfiguration
添加到 @Configuration 类(而不是 PropertySource 注释),但它所做的只是在找不到请求的属性时中断。
SpringBoot is supposed to resolve the properties automatically from the standard application.properties
file, why this behaviour? SpringBoot 应该从标准的application.properties
文件中自动解析属性,为什么会出现这种行为? Using version 2.2.2.RELEASE使用版本 2.2.2.RELEASE
Update:更新:
The answers are correct, the reason it was not working was that I was calling these properties in a test.答案是正确的,它不起作用的原因是我在测试中调用了这些属性。 Annotating the test with @SpringBootTest
fixes the issue.使用@SpringBootTest
注释测试可以解决此问题。 In fact when the application is running it is @SpringBootApplication
that does the magic事实上,当应用程序运行时,它是@SpringBootApplication
作用
As you can read in this article (chapter 5) , SpringBoot manage automatically the application.properties
file.正如您在本文(第 5 章)中所读到的,SpringBoot 自动管理application.properties
文件。
I don't know if this is your problem because I've not seen the code, but in Spring Boot the Application
class should be annotated with @SpringBootApplication
.我不知道这是否是您的问题,因为我还没有看到代码,但是在 Spring Boot 中, Application
类应该用@SpringBootApplication
进行注释。
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
Take a look at this starting example .看看这个起始示例。
You can then inject the value for example in a controller class in this way:然后,您可以通过这种方式在控制器类中注入值:
@RestController
public class HelloController {
@Value("${test}")
private String test;
@RequestMapping("/test")
String hello() {
return test;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.