如何在Spring boot中修改默认端口java
Spring boot为应用程序提供了不少属性的默认值。可是有时候,咱们须要自定义某些属性,好比:修改内嵌服务器的端口号。spring
本篇文章就来讨论这个问题。服务器
第一种方式,也是最经常使用的方式就是在属性文件中,覆盖默认的配置。对于服务器的端口来讲,该配置就是:server.port。app
默认状况下,server.port值是8080。 咱们能够在application.properties中这样修改成8081:ide
server.port=8081
若是你使用的是application.yml,那么须要这样配置:函数
server: port : 8081
这两个文件都会在Spring boot启动的时候被加载。spring-boot
若是同一个应用程序须要在不一样的环境中使用不一样的端口,这个时候你就须要使用到Spring Boot的profile概念,不一样的profile使用不一样的配置文件。 命令行
好比你在application-dev.properties中:code
server.port=8081
在application-qa.properties 中:server
server.port=8082
咱们能够在程序中直接指定应用程序的端口,以下所示:
@SpringBootApplication public class CustomApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(CustomApplication.class); app.setDefaultProperties(Collections .singletonMap("server.port", "8083")); app.run(args); } }
另一种自定义服务的方法就是实现WebServerFactoryCustomizer接口:
@Component public class ServerPortCustomizer implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> { @Override public void customize(ConfigurableWebServerFactory factory) { factory.setPort(8086); // factory.setAddress(""); } }
使用ConfigurableWebServerFactory能够自定义包括端口在内的其余不少服务器属性。
若是应用程序被打包成jar,咱们也能够在命令行运行时候,手动指定 server.port 。
java -jar spring-5.jar --server.port=8083
或者这样:
java -jar -Dserver.port=8083 spring-5.jar
上面咱们将了这么多修改自定义端口的方式,那么他们的生效顺序是怎么样的呢?
更多教程请参考 flydean的博客