修改SpringBoot应用程序默认端口

本文介绍了在SpringBoot中修改服务器默认端口的三种方式:1)application.properties文件配置;2)命令行设置(对WinSW无效);3)使用WebServerFactoryCustomizer自定义。推荐使用第三种方法,确保代码级的控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

写在前面

今天需要在一台服务器上同时部署多个相同的SpringBoot应用程序,需要修改下SpringBoot 默认端口,以下是3种常用的方式,最后选择了第三种,用代码直接设定了。

实现方式

1.在application.properties文件中配置 server.port = 9090,这种方式最常被使用但执行优先级最低,会被后面的方式覆盖;application.properties 文件需要放在 src/main/resources 下面。

2.用命令行设置端口

java -jar target.jar -server.port = 9090

 这个方式放在WinSW的启动参数里面不生效,具体原因还待研究。

3.在代码里面通过WebServerFactoryCustomizer实现,在Spring Boot2.0以上的版本中EmbeddedServletContainerCustomizer类被WebServerFactoryCustomizer替代了;具体代码如下:

org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.WebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CustomConfig implements WebServerFactoryCustomizer {
    //定制嵌入式的servlet容器
    //在Spring Boot2.0以上配置嵌入式Servlet容器时EmbeddedServletContainerCustomizer类被WebServerFactoryCustomizer替代
    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer(){
        return new WebServerFactoryCustomizer<ConfigurableWebServerFactory>(){
            //定制嵌入式的servlet容器相关的规则
            @Override
            public void customize(ConfigurableWebServerFactory factory) {
                factory.setPort(9090);
            }
        };
    }

    @Override
    public void customize(WebServerFactory factory) {

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值