第一种方式咱们只须要在application.properties中加这样的一句话就能够了:server.port=8004。为何这种方式能够实现修改SpringBoot的默认端口呢?由于在SpringBoot中有这样的一个类:ServerProperties。咱们能够大体看一下这个类:html
@ConfigurationProperties(prefix = "server", ignoreUnknownFields = true) public class ServerProperties implements EmbeddedServletContainerCustomizer, EnvironmentAware, Ordered { /** * Server HTTP port. */ private Integer port;
在这个类里有一个@ConfigurationProperties注解,这个注解会读取SpringBoot的默认配置文件application.properties的值注入到bean里。这里定义了一个server的前缀和一个port字段,因此在SpringBoot启动的时候会从application.properties读取到server.port的值。咱们接着往下看一下:
java
@Override public void customize(ConfigurableEmbeddedServletContainer container) { if (getPort() != null) { container.setPort(getPort()); }
这里有一个customize的方法,这个方法里会给SpringBoot设置读取到的端口号。web
咱们在上面看到了端口号是在customize这个方法中设置的,而这个方法是在EmbeddedServletContainerCustomizer这个接口中的,因此咱们能够实现这个接口,来更改SpringBoot的默认端口号。具体代码以下:spring
@RestController @EnableAutoConfiguration @ComponentScan public class FirstExample implements EmbeddedServletContainerCustomizer { @RequestMapping("/first.do") String home() { return "Hello World!世界你好!O(∩_∩)O哈哈~!!!我不是太很好!"; } public static void main(String[] args) { SpringApplication.run(FirstExample.class, args); } @Override public void customize(ConfigurableEmbeddedServletContainer configurableEmbeddedServletContainer) { configurableEmbeddedServletContainer.setPort(8003); } }
而后你在启动SpringBoot的时候,发现端口号被改为了8003.tomcat
在启动类中添加servletContainer方法app
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Bean public TomcatServletWebServerFactory servletContainer(){ return new TomcatServletWebServerFactory(8081) ; } }
若是你只是想在启动的时候修改一次端口号的话,能够用命令行参数来修改端口号。配置以下:java -jar 打包以后的SpringBoot.jar --server.port=8000ide
你一样也能够把修改端口号的配置放到JVM参数里。配置以下:-Dserver.port=8009。 这样启动的端口号就被修改成8009了。编码
能够根据本身的业务需求,选择相应的配置方式。spa
转自:SpringBoot修改默认端口号.net