I\'m starting up a Spring Boot application with mvn spring-boot:run
.
One of my @Controller
s needs information about the host and port the a
I have just found a way to get server ip and port easily by using Eureka client library. As I am using it anyway for service registration, it is not an additional lib for me just for this purpose.
You need to add the maven dependency first:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
Then you can use the ApplicationInfoManager service in any of your Spring beans.
@Autowired
private ApplicationInfoManager applicationInfoManager;
...
InstanceInfo applicationInfo = applicationInfoManager.getInfo();
The InstanceInfo object contains all important information about your service, like IP address, port, hostname, etc.
You can get network interfaces with NetworkInterface.getNetworkInterfaces()
, then the IP addresses off the NetworkInterface objects returned with .getInetAddresses()
, then the string representation of those addresses with .getHostAddress()
.
If you make a @Configuration
class which implements ApplicationListener<EmbeddedServletContainerInitializedEvent>
, you can override onApplicationEvent
to get the port number once it's set.
@Override
public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
int port = event.getEmbeddedServletContainer().getPort();
}
You can get hostname from spring cloud property in spring-cloud-commons-2.1.0.RC2.jar
environment.getProperty("spring.cloud.client.ip-address");
environment.getProperty("spring.cloud.client.hostname");
spring.factories of spring-cloud-commons-2.1.0.RC2.jar
org.springframework.boot.env.EnvironmentPostProcessor=\
org.springframework.cloud.client.HostInfoEnvironmentPostProcessor