Reputation: 301
How to properly inject value from application.properties file?
main class:
@SpringBootApplication
public class Main {
public static void main(String args[]) {
SpringApplication.run(Main.class,args);
}
application.properties file:
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
Upvotes: 0
Views: 940
Reputation: 301
@pvpkiran I am trying to add this to my main method, rest is unchanged.
@SpringBootApplication
public class Application {
@Autowired
static Test t;
public static void main(String args[]){
SpringApplication.run(Application.class,args);
t.foobar();
}
}
Upvotes: 0
Reputation: 27048
Properties are not injected when the class is being created (i.e when your constructor is called), but a bit later. Hence you see null in the constructor.
Try adding a method annotated with @PostConstruct
like this and check the result:
@PostConstruct
public void afterCreation(){
System.out.println("@@@@@@@@@@@@@@@@@@@"+ mypassword);
}
Upvotes: 2