How to configure port for a Spring Boot application

前端 未结 30 1238
名媛妹妹
名媛妹妹 2020-11-22 13:36

How do I configure the TCP/IP port listened on by a Spring Boot application, so it does not use the default port of 8080.

30条回答
  •  北海茫月
    2020-11-22 14:22

    To extend other answers:

    There is a section in the docs for testing which explains how to configure the port on integration tests:

    • 41.3 Testing Spring Boot applications
    • 41.3.3 Working with random ports

    At integration tests, the port configuration is made using the annotation @SpringBootTest and the webEnvironment values.


    Random port:

    @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)
    

    You can inject the value using @LocalServerPort which is the same as @Value("${local.server.port}").

    • Example:

    Random port test configuration:

    @RunWith(SpringRunner.class
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    public class ExampleTest {
       ...
       @LocalServerPort //to inject port value
       int port;
    }
    

    Defined port:

    @SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)
    

    It takes the value from server.port if is defined.

    • If is defined using @TestPropertySource(properties = "server.port=9192"), it overrides other defined values.
    • If not, it takes the value from src/test/resources/application.properties (if exists).
    • And finally, if it is not defined it starts with the default 8080.

    Example:

    Defined port test configuration:

    @RunWith(SpringRunner.class)
    @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
    @TestPropertySource(properties = "server.port=9192")
    public class DemoApplicationTests {
    
        @Test
        public void contextLoads() {
        }
    
    }
    

提交回复
热议问题