Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lamjar/75400f48ca09df195a6ac3102b302934 to your computer and use it in GitHub Desktop.
Save lamjar/75400f48ca09df195a6ac3102b302934 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