# 使用 maven spring-boot:run 修改默认端口

mvn spring-boot:run -Dspring-boot.run.arguments=--server.port=8085

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

参考 https://stackoverflow.com/questions/21083170/how-to-configure-port-for-a-spring-boot-application (opens new window)

# 修改端口的多种姿势(不限于修改端口,也可以修改其他属性)

various configuration externalization mechanism (opens new window)

  1. Pass property through command line argument as application argument

    java -jar <path/to/my/jar> --server.port=7788
    
  2. From property in SPRING_APPLICATION_JSON (Spring Boot 1.3.0+)

    • Define environment variable in U*IX shell:

      SPRING_APPLICATION_JSON='{"server.port":7788}' java -jar <path/to/my/jar>
      
    • By using Java system property:

      java -Dspring.application.json='{"server.port":7788}' -jar <path/to/my/jar>
      
    • Pass through command line argument:

      java -jar <path/to/my/jar> --spring.application.json='{"server.port":7788}'
      
  3. Define JVM system property

    java -Dserver.port=7788 -jar <path/to/my/jar>
    
  4. Define OS environment variable

    • U*IX Shell

      SERVER_PORT=7788 java -jar <path/to/my/jar>
      
    • Windows

      SET SERVER_PORT=7788
      java -jar <path/to/my/jar>
      
  5. Place property in ./config/application.properties configuration file

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  6. Place property in ./config/application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    
  7. Place property in ./application.properties

    server.port=7788
    

    and run:

     java -jar <path/to/my/jar>
    
  8. Place property in ./application.yaml

    server:
        port: 7788
    

    and run:

     java -jar <path/to/my/jar>
    

# 使用程序修改属性

@Configuration
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
        return (container -> {
            container.setPort(8012);
        });
    }
}

或者

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

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

# 随机端口

server.port=0