Home > Net >  String.format returns null in Spring Boot after retrieving information from application.properties
String.format returns null in Spring Boot after retrieving information from application.properties

Time:02-01

I have a Spring Boot application, using Intellij, and am trying to use the @Value annotation in order to get an environment variable from my application.properties.

My application.properties looks like this

server.port=27019
web.entrance.id=63d284ec

Using debugger, I can see that the value of entranceId is successfully retrieved from application.properties, but the same variable is always null in the String.format and my WebUrl has the string 'null' in it and I don't understand why.

@RestController
public class Controller {

  @Value(("${entrance.id}"))
  private String entranceId;

  String WebUrl = String.format("http://localhost:27019/%s", entranceId);

Can someone explain if there is some detail I'm missing why this happens? Thank you

CodePudding user response:

Your thinking is wrong. Spring will process the @Value after the object has been constructed, whereas your field is being initialized as soon as the class is being constructed (so during constructing).

Basically what Spring does

  1. new Controller()
  2. Detect @Value and with reflection set value
  3. Any construction callbacks (like @PostConstruct).

Your field is being filled at step 1 not after step 2. At which point the @Value hasn't yet been processed.

If you want to set the value you need to do that in an @PostConstruct method or use constructor injection to construct the URL.

  • Related