0

I'm using Spring Boot and I want to know if there is a defined way or some open source library to make secure the connection establishing.

For example the default port is 8080, so I would set the port to 8081 if the port is already in use, instead of make the application to fail the start.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
osharko
  • 204
  • 3
  • 19
  • 2
    Possible duplicate of [How to configure port for a Spring Boot application](https://stackoverflow.com/questions/21083170/how-to-configure-port-for-a-spring-boot-application) – lealceldeiro Oct 26 '18 at 14:58

2 Answers2

2

Add to your property file server.port=0and spring boot will automatically pick the available port.

See docs (section 75.7 - here is a good example to solve your issue).

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
  • This is not what he meant, that solution simply "randomizes" the port selection. My guess is that he wanted to change the port in case if that same port is used by i.e. other application/program on his server – SadmirD Oct 26 '18 at 15:09
  • And that's why I voted for your solution ;) @SadmirD – Rostyslav Barmakov Oct 26 '18 at 15:11
  • Thanks, only later i found the same docs and found that it's not only random, but also check for an avaible port :) – osharko Oct 26 '18 at 15:15
  • Rostyslav Barmakov, now I noticed that your answer is actually the exact thing that @osh arko asked, so your answer should be labelled as correct one. Not sure why people voted it as off-topic, OP should just re-phrase the question since it is a legitimate one but he used a bad choice of words, it's not about "secure connection establishing" but about elegant resolving of a scenario where the chosen port is already in use. – SadmirD Oct 26 '18 at 20:14
1

I am just throwing the idea for you to reconsider, it's not production-ready and requires some polishing, but you could definitely try something like this in your main method:

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {

        SpringApplication app = new SpringApplication(MyApplication.class);
        int serverPort = 8080;
        do {
            try {
                app.setDefaultProperties( Collections.singletonMap( "server.port", Integer.toString(serverPort) ) );
                app.run(args);
            } catch (Exception e) {
                serverPort++;
            }
        } while (serverPort < 9000);
    }
}

As you might have noticed, this should theoretically attempt to set up port again and again in case of an error. I limited it to port 9000, but you can try to tinker a solution that better suits what you intended to do and adjust it in your specific use-case scenario.

SadmirD
  • 642
  • 3
  • 8
  • Thank you, but i was looking for something like port=0, that enable the same logic you used, but automatically – osharko Oct 26 '18 at 15:16