[英]@Value from application.properties in SpringBoot gives null all the time
How to properly inject value from application.properties file? 如何正确地从application.properties文件中注入值?
main class: 主类:
@SpringBootApplication
public class Main {
public static void main(String args[]) {
SpringApplication.run(Main.class,args);
}
application.properties file: application.properties文件:
my.password=admin
test class: 测试类别:
@Component
public class Test {
@Value("${my.password}")
private String mypassword;
public String getMypassword() {
return mypassword;
}
public void setMypassword(String mypassword) {
this.mypassword = mypassword;
}
public Test(){
System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
}
}
Console prints always null, not the value from application
file 控制台始终打印为空,而不打印application
文件中的值
Properties are not injected when the class is being created (ie when your constructor is called), but a bit later. 在创建类时(即,在调用构造函数时)不会注入属性,但会稍后。 Hence you see null in the constructor. 因此,您在构造函数中看到null。
Try adding a method annotated with @PostConstruct
like this and check the result: 尝试添加带有@PostConstruct
注释的方法,如下所示,并检查结果:
@PostConstruct
public void afterCreation(){
System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
}
@pvpkiran I am trying to add this to my main method, rest is unchanged. @pvpkiran我正在尝试将其添加到我的主要方法中,其余部分保持不变。
@SpringBootApplication
public class Application {
@Autowired
static Test t;
public static void main(String args[]){
SpringApplication.run(Application.class,args);
t.foobar();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.