Spring's Environment holds this information for you.
@Autowired
Environment environment;
String port = environment.getProperty("local.server.port");
On the surface this looks identical to injecting a field annotated @Value("${local.server.port}")
(or @LocalServerPort
, which is identical), whereby an autowiring failure is thrown at startup as the value isn't available until the context is fully initialised. The difference here is that this call is implicitly being made in runtime business logic rather than invoked at application startup, and hence the 'lazy-fetch' of the port resolves ok.