I created a simple SpringBoot application using "http://start.spring.io" Spring Initializr. I am using JDK 8 and Spring 2.6.6.
I opened an application in IntelliJ and was able to build it and run it. I also added "application.properties" as my resource where I defined a property :
application.baseurl=/responsiblityViewer/api
in my DemoApplication.java :
public class DemoApplication {
@Value("${application.baseurl}")
public static String baseUrl;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
System.out.println("Test Application baseUrl : " baseUrl);
}
}
The output is NULL.
I also tried to use "application.yml" where I defined :
application:
baseurl: /responsiblityViewer/api
and still "application.baseurl" is not getting injected. What am I doing wrong here?
CodePudding user response:
There's a lot to dissect here.
First, you can't inject a value into a static property.
Second, you will not be able to reference that property from a static main method as the bean hasn't been constructed yet.
If you read up on the spring bean lifecycle it will help you to understand this, the injection occurs after instantiation.
You can observe this behavior if you change your variable definition to
public String baseUrl;
and add this method
@PostConstruct
public void printIt() {
log.debug(baseUrl);
}