Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting values from application.properties in SpringBoot application

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading