[BAEL-4612] get spring boot port at runtime

This commit is contained in:
Kai Yuan
2020-09-22 00:41:23 +02:00
parent 10e7aaed73
commit 8b0b645e6f
6 changed files with 126 additions and 0 deletions
@@ -0,0 +1,12 @@
package com.baeldung.serverport;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class GetServerPortApplication {
public static void main(String[] args) {
SpringApplication.run(GetServerPortApplication.class, args);
}
}
@@ -0,0 +1,20 @@
package com.baeldung.serverport;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
@Service
public class ServerPortService {
private int port;
public int getPort() {
return port;
}
@EventListener
public void onApplicationEvent(final ServletWebServerInitializedEvent event) {
port = event.getWebServer().getPort();
}
}