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


当前回答

延伸其他答案:

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

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() {
    }

}

其他回答

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

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

您可以在下面的方法中添加端口。

执行->配置命令 在application.xml中添加server.port=XXXX

将此添加到应用程序中。属性文件

server.port= 8080

除了所有的答案,我想指出的是,大多数IDE (IntelliJ与Spring插件,STS)都有一个功能,它建议SpringBoot支持的所有配置键。(即所有自以为是的配置关键字)

Spring插件Intellij

这招对我很管用:

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

@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);
    }
}

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