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


当前回答

Spring-web模块默认提供了一个运行在端口号8080上的嵌入式tomcat服务器。

您可以修改如下-

A)如果你使用gradle,那么可以在你的应用程序中设置属性。yml:

 server:  
      port: 8042

B)如果你正在使用maven,那么你可以在你的应用程序中设置属性。属性:

server.port: 8042

C)当你在自己的配置文件中有端口,并想在运行时设置它。

通过实现WebServerFactoryCustomizer接口- Spring 2.x

@Component
public class MyTomcatWebServerCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        // customize the factory here
        factory.setPort(8042);
    }
}

通过实现EmbeddedServletContainerCustomizer接口- Spring 1.x

@Component
public class CustomizationBean implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        // customize here
        container.setPort(8042);
    }
}

其他回答

只要申请一下。src/main/resources中的属性

server.port=****

其中****为端口号。

希望这篇文章能有所帮助

application.properties=> 

server.port=8090

application.yml=> 

server
  port:8090

服务器。对于随机端口,Port = 0

服务器。端口= 8080为自定义8080端口

在应用程序中。资源中的属性文件:

server.port=8082

由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