How could I get the host and port where my application is deployed during run-time so that I can use it in my java method?
You can get this information via Environment for the port and the host you can obtain by using InternetAddress . Getting the port this way will only work, if a) the port is actually configured explicitly, and b) it is not set to 0 (meaning the servlet container will choose a random port on startup).
The Spring Boot framework provides the default embedded server (Tomcat) to run the Spring Boot application. It runs on port 8080.
You can get this information via Environment
for the port
and the host
you can obtain by using InternetAddress
.
@Autowired Environment environment; // Port via annotation @Value("${server.port}") int aPort; ...... public void somePlaceInTheCode() { // Port environment.getProperty("server.port"); // Local address InetAddress.getLocalHost().getHostAddress(); InetAddress.getLocalHost().getHostName(); // Remote address InetAddress.getLoopbackAddress().getHostAddress(); InetAddress.getLoopbackAddress().getHostName(); }
If you use random port like server.port=${random.int[10000,20000]}
method. and in Java code read the port in Environment
use @Value
or getProperty("server.port")
. You will get a Unpredictable Port Because it is Random.
ApplicationListener, you can override onApplicationEvent to get the port number once it's set.
In Spring boot version Implements Spring interface ApplicationListener<EmbeddedServletContainerInitializedEvent>
(Spring boot version 1) or ApplicationListener<WebServerInitializedEvent>
(Spring boot version 2) override onApplicationEvent to get the Fact Port .
Spring boot 1
@Override public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) { int port = event.getEmbeddedServletContainer().getPort(); }
Spring boot 2
@Override public void onApplicationEvent(WebServerInitializedEvent event) { Integer port = event.getWebServer().getPort(); this.port = port; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With