In some situations the value of the randomly assigned port is needed for other configuration properties. It would be usefull to be able to use the placeholder in configuration files.
Take this simple example :
example:
url: http://localhost:${local.server.port}
Because this information is not available when the properties are read the value for url property remains "as-is".
The work-around that I use today is to register an ApplicationListener<EmbeddedServletContainerInitializedEvent>
and update the values manually.
@Component
public class LocalPortInitializedListener implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {
@Autowired
private Environment environment;
@Autowired
private ExampleConfigurationProperties configurationProperties;
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
String localServerPort = environment.getProperty("local.server.port");
String url = "http://localhost:" + localServerPort;
configurationProperties.setUrl(url);
}
}
Because my use-case is simple the above configuration works but if there was another property that depended on example.url
things would get ugly. (fair to say I don't know if it's worth thinking that far ahead)
Please let me know if there is currently a better way to do this.
I am afraid we can't make that happen. The way local.server.port
is handled makes it impossible to work the way you want there. Do you know that the TestRestTemplate
is automatically configured to talk to the right port?
TestRestTemplate is fine to run "REST"-based test, but some beans (not test code) may rely on port (for example in a standalone distribution) or used other protocol (e.g. SOAP).
Can you provide some tips/snippets/examples in order to inject local server port during Spring initialization ?
@loganmzz this issue is closed and we don't use the tracker for questions anyway. Please join us on Gitter or ask on StackOverflow.
Most helpful comment
TestRestTemplate is fine to run "REST"-based test, but some beans (not test code) may rely on port (for example in a standalone distribution) or used other protocol (e.g. SOAP).
Can you provide some tips/snippets/examples in order to inject local server port during Spring initialization ?