Skip to content

Instantly share code, notes, and snippets.

@BorzdeG
Created September 15, 2015 11:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save BorzdeG/87a5ec1e70eb0b51e033 to your computer and use it in GitHub Desktop.
Save BorzdeG/87a5ec1e70eb0b51e033 to your computer and use it in GitHub Desktop.
Spring Boot :: set random server port
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