如何配置Spring Boot应用程序侦听的TCP/IP端口,使其不使用默认端口8080。


当前回答

如果端口号可以是随机的,则可以在应用程序中使用随机函数。属性server.port = $ {random.int (4)}

其他回答

延伸其他答案:

文档中有一个测试部分解释了如何在集成测试中配置端口:

41.3测试Spring Boot应用程序 41.3.3使用随机端口


在集成测试中,端口配置是使用注释@SpringBootTest和webEnvironment值完成的。


随机端口:

@SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT)

您可以使用与@Value("${local.server.port}")相同的@LocalServerPort注入值。

例子:

随机端口测试配置:

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

定义端口:

@SpringBootTest(webEnvironment=WebEnvironment.DEFINED_PORT)

它从服务器获取值。端口,如果已定义。

如果使用@TestPropertySource(properties = "server.port=9192")定义,它将覆盖其他定义的值。 如果不是,则从src/test/resources/application获取值。属性(如果存在)。 最后,如果没有定义它,则从默认的8080开始。

例子:

定义端口测试配置:

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

    @Test
    public void contextLoads() {
    }

}

在application.properties中包含下面的属性

server.port=8080

由Gradle运行:

在默认端口(8080)运行:./gradlew bootRun 运行在提供的端口(8888):./gradlew bootRun——args='——server.port=8888' 如果应用中有变量。PORT=8888 ./gradlew bootRun . properties文件

由Maven运行:

Run in default port(8080): mvnw spring-boot:run Run in provided port(8888): mvnw spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085' Run in provided port(8888): mvn spring-boot:run -Dspring-boot.run.arguments='--server.port=8085' Run in provided port(8888) with other custom property: mvn spring-boot:run -Dspring-boot.run.arguments="--server.port=8899 --your.custom.property=custom" If we have any variable in the application.properties file named PORT, run this: SERVER_PORT=9093 mvn spring-boot:run

使用java -jar:

Create the .jar file: For Gradle: ./gradlew clean build. We will find the jar file inside: build/libs/ folder. For Maven: mvn clean install. We will find the jar file inside:target folder. Run in default port(8080): java -jar myApplication. jar Run in provided port(8888): java -jar myApplication.jar --port=8888 Run in provided port(8888): java -jar -Dserver.port=8888 myApplication.jar Run in provided port(8888) having variable SERVER_PORT in application.properties file: SERVER_PORT=8888 java -jar target/myApplication.jar

服务器端口声明有两种类型

1.静态类型

   server.port=8080. // your port number

动态类型 server.port = 0。//随机生成端口号。 server.port = ${端口:0}

打开应用程序。属性文件。并在属性文件中添加下面的属性。

server.port = 1443

这将很好地工作,您可以根据自己的愿望设置任何端口号。