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


当前回答

您可以在应用程序中配置端口。属性文件或应用程序。Yaml文件,在src/main/resources中。

server.port=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);
    }
}

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

这个问题是Gradle Spring Port的第一个结果。

如果你使用gradle,你可以这样做,如果你有Spring Boot gradle插件已经应用:

bootRun {
    args += ["--server.port=[PORT]"]
}

想知道更复杂的答案,请看我的回答。

你可以在java代码中设置port:

HashMap<String, Object> props = new HashMap<>();
props.put("server.port", 9999);

new SpringApplicationBuilder()
    .sources(SampleController.class)                
    .properties(props)
    .run(args);

或者在application.yml中:

server:
    port: 9999

或者在application.properties中:

server.port=9999

或者作为命令行参数:

-Dserver.port=9999

使用mvn shell命令行,spring-boot 2:

mvn spring-boot:run -Dspring-boot.run.jvmArguments='-Dserver.port=8085'

在spring引导中,您可以轻松地在应用程序中配置服务公开端口。属性文件。

server.port=portnumber

如果您没有专门设置端口,那么它将尝试使用端口80打开服务。如果它已经被使用,则嵌入容器上的服务将不会启动。