How to get the SPRING Boot HOST and PORT address during run time?
Matthew Harrington
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?
26 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();
} 4 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;
} Here is an util component:
EnvUtil.java
(Put it in proper package, to become a component.)
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.net.InetAddress;
import java.net.UnknownHostException;
/** * Environment util. */
@Component
public class EnvUtil { @Autowired Environment environment; private String port; private String hostname; /** * Get port. * * @return */ public String getPort() { if (port == null) port = environment.getProperty("local.server.port"); return port; } /** * Get port, as Integer. * * @return */ public Integer getPortAsInt() { return Integer.valueOf(getPort()); } /** * Get hostname. * * @return */ public String getHostname() throws UnknownHostException { // TODO ... would this cache cause issue, when network env change ??? if (hostname == null) hostname = InetAddress.getLocalHost().getHostAddress(); return hostname; } public String getServerUrlPrefi() throws UnknownHostException { return "http://" + getHostname() + ":" + getPort(); }
}Example - use the util:
Then could inject the util, and call its method.
Here is an example in a controller:
// inject it,
@Autowired
private EnvUtil envUtil;
/** * env * * @return */
@GetMapping(path = "/env")
@ResponseBody
public Object env() throws UnknownHostException { Map<String, Object> map = new HashMap<>(); map.put("port", envUtil.getPort()); map.put("host", envUtil.getHostname()); return map;
} For the Host: As mentionned by Anton
// Local address
InetAddress.getLocalHost().getHostAddress();
InetAddress.getLocalHost().getHostName();
// Remote address
InetAddress.getLoopbackAddress().getHostAddress();
InetAddress.getLoopbackAddress().getHostName();Port: As mentioned by Nicolai, you can retrieve this information by the environment property only if it is configured explicitly and not set to 0.
Spring documentation on the subject:
For the actual way to do this, it was answered here:Spring Boot - How to get the running port
And here's a github example on how to implement it:
Just a complete example for answers above
package bj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import java.net.InetAddress;
import java.net.UnknownHostException;
@SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection")
@SpringBootApplication
class App implements ApplicationListener<ApplicationReadyEvent> { @Autowired private ApplicationContext applicationContext; public static void main(String[] args) { SpringApplication.run(App.class, args); } @Override public void onApplicationEvent(ApplicationReadyEvent event) { try { String ip = InetAddress.getLocalHost().getHostAddress(); int port = applicationContext.getBean(Environment.class).getProperty("server.port", Integer.class, 8080); System.out.printf("%s:%d", ip, port); } catch (UnknownHostException e) { e.printStackTrace(); } }
} The port has been bind in runtime could been injected as:
@Value('${local.server.port}')
private int port;