Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the SPRING Boot HOST and PORT address during run time?

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?

like image 849
Anezka L. Avatar asked Aug 12 '16 10:08

Anezka L.


People also ask

How do I find my host and Spring boot port?

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).

Which port is Spring boot running?

The Spring Boot framework provides the default embedded server (Tomcat) to run the Spring Boot application. It runs on port 8080.


2 Answers

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(); } 
like image 50
Anton N Avatar answered Oct 12 '22 12:10

Anton N


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; } 
like image 32
Gim Lyu Avatar answered Oct 12 '22 12:10

Gim Lyu