Forked from BorzdeG/Spring.Boot.Server.Random.Port.java
Created
January 15, 2018 15:26
-
-
Save lamjar/75400f48ca09df195a6ac3102b302934 to your computer and use it in GitHub Desktop.
Spring Boot :: set random server port
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration; | |
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; | |
import org.springframework.context.annotation.Configuration; | |
import java.io.IOException; | |
import java.net.ServerSocket; | |
@Configuration | |
public class ServerPropertiesConfiguration extends ServerPropertiesAutoConfiguration { | |
@SuppressWarnings("unused") private static final Logger LOG = LoggerFactory.getLogger( | |
ServerPropertiesConfiguration.class.getName()); | |
@Override | |
public void customize(ConfigurableEmbeddedServletContainer container) { | |
container.setPort(findRandomOpenPortOnAllLocalInterfaces()); | |
super.customize(container); | |
} | |
private int findRandomOpenPortOnAllLocalInterfaces() { | |
int port = 0; | |
try (ServerSocket socket = new ServerSocket(port)) { | |
port = socket.getLocalPort(); | |
socket.close(); | |
} catch (IOException ignored) { | |
} | |
LOG.debug("port: {}", port); | |
return port; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment