Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot - How to get the running port

I have a spring boot application (using embedded tomcat 7), and I've set server.port = 0 in my application.properties so I can have a random port. After the server is booted up and running on a port, I need to be able to get the port that that was chosen.

I cannot use @Value("$server.port") because it's zero. This is a seemingly simple piece of information, so why can't I access it from my java code? How can I access it?

like image 252
Tucker Avatar asked May 18 '15 20:05

Tucker


People also ask

How do I run a Spring Boot application on a random port?

For example, in the application.properties file, we can set 7777 as the port our application is running on: Alternatively, instead of defining a fixed port, we can let the Spring Boot application run on a random port by setting “0” as the value of the “server.port” property:

How do I set the HTTP port in Spring Boot?

2.2. Two Scenarios of Setting the Port Usually, the most straightforward way to configure the HTTP port of a Spring Boot application is by defining the port in the configuration file application.properties or application.yml. For example, in the application.properties file, we can set 7777 as the port our application is running on:

Why doesn't @springboottest start with a port?

This is because @SpringBootTest defaults to a MockMVC environment, not starting an apllication server that could provide a port. Thanks to @Dirk Lachowski for pointing me in the right direction.

What is @localserverport in Spring Boot?

@LocalServerPort is just a shortcut for @Value ("$ {local.server.port}"). Using webEnvironment = WebEnvironment.RANDOM_PORT resolved the issue. Thanks Spring's Environment holds this information for you. @Autowired Environment environment; String port = environment.getProperty ("local.server.port");


1 Answers

Is it also possible to access the management port in a similar way, e.g.:

  @SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)   public class MyTest {      @LocalServerPort     int randomServerPort;      @LocalManagementPort     int randomManagementPort; 
like image 86
LaughingLemon Avatar answered Sep 17 '22 17:09

LaughingLemon