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?
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:
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:
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.
@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");
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With