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


当前回答

这招对我很管用:

增加了一个自定义容器类:

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
       configurableEmbeddedServletContainer.setPort(8888);
    }

}

但这仍然没有使用端口8888。

然后我设置“scanBasePackages”属性就像这样在“@SpringBootApplication”类上我的主要方法:(scanBasePackages ={"自定义容器包"})

@SpringBootApplication(scanBasePackages = {"com.javabrains.util"})
public class CourseApiApp {

    public static void main (String args []) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

它开始拾取自定义容器中的端口集。

其他回答

这招对我很管用:

增加了一个自定义容器类:

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) {
       configurableEmbeddedServletContainer.setPort(8888);
    }

}

但这仍然没有使用端口8888。

然后我设置“scanBasePackages”属性就像这样在“@SpringBootApplication”类上我的主要方法:(scanBasePackages ={"自定义容器包"})

@SpringBootApplication(scanBasePackages = {"com.javabrains.util"})
public class CourseApiApp {

    public static void main (String args []) {
        SpringApplication.run(CourseApiApp.class, args);
    }
}

它开始拾取自定义容器中的端口集。

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

server.port=8080

“服务器。Port =8080"将只工作,如果你运行应用程序作为一个jar通过main方法,

如果您通过tomcat容器将此应用程序作为war文件运行,则此配置将不起作用。

由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

您可以通过在您的配置(基于java或xml)中覆盖EmbeddedServletContainerFactory bean来指定端口。在这里,您可以为所使用的嵌入式servlet容器指定端口。请参阅Spring Boot - Core“嵌入式Servlet容器支持”段落和示例。希望这能有所帮助。