user5167041 user5167041 - 1 month ago 9
Java Question

Spring Boot- Fail to retrieve application.yml variable value using @Value

I am trying to retrieve my base_url that is stored in the application.yml from my @RestController. However, when I use the code printed below, it always return null. Can someone please let me know why @Value("${base_url}") always return null? Thanks in advance.

Rest Controller:

@RestController
public class AccountController {

@Value("${company.department.base_url}")
static String base_url;

@RequestMapping(method = RequestMethod.GET, value = "/getAccount")
public ResponseEntity<Object> getAccount() {
//getAccountCode
}
}


application.yml:

company:
department:
base_url: https://www.test.com


TestApplication.java

@SpringBootApplication
public class TestApplication {

public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}

Answer

You can't use static field, then you should do this:

@Value("${company.department.base_url}")
String base_url;

Or try a workaround for that: https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

Comments