0

Spring-boot has random port generation as described here. But this example about web configuration. Is there a way to generate random port number, check that it is avalible, and reserve it for bean creation? E.g. something like that:

@Bean
public void myBean (@Value("${somePort}") String port) {
    return new MyBean(port);
}

Please note, that spring has random properties like ${random.int} but this does not garante that port is free to use.

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
Cherry
  • 31,309
  • 66
  • 224
  • 364

1 Answers1

0

To know if a port is available to use or not, the simple test os try to open that port and see if there is no error. If it is ok, then you are free to use it. There are several answers here in SO how to do it:

Sockets: Discover port availability using Java

If you want a random port every time, just use 0. It will use the next available port:

import java.io.IOException;
import java.net.ServerSocket;

public class DemoApplication {

    public static void main(String[] args) {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);

            System.out.println(socket.getLocalPort());
            socket.accept();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null)
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    }
}
Community
  • 1
  • 1
Sigrist
  • 1,471
  • 2
  • 14
  • 18