SpringBoot2.0 用WebServerFactoryCustomizer 设置端口号

本文介绍了如何在SpringBoot 1.5.x和2.x.x版本中通过自定义配置实现更改应用服务器默认端口的方法。对于SpringBoot 1.5.x,可以通过实现EmbeddedServletContainerCustomizer接口并覆盖customize方法来设置端口号;对于SpringBoot 2.x.x,则需使用WebServerFactoryCustomizer接口的实现来完成相同功能。

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

//SpringBoot1.5.x
@Bean
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer(){
    return new EmbeddedServletContainerCustomizer() {
        @Override
        public void customize(ConfigurableEmbeddedServletContainer container) {
            container.setPort(8090);
        }
    };
}

//SpringBoot2.x.x
@Bean
    public WebServerFactoryCustomizer webServerFactoryCustomizer(){
        return new WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>() {
            @Override
            public void customize(ConfigurableServletWebServerFactory factory) {
                factory.setPort(8090);
            }
        };
    }
--------------------- 
作者:Silverfeathers 
来源:优快云 
原文:https://blog.youkuaiyun.com/Silverfeathers/article/details/81369297 
版权声明:本文为博主原创文章,转载请附上博文链接!

 

在Spring Boot 2.0及以上版本中,可以通过以下步骤配置两个端口: 1. 在`application.properties`或`application.yml`配置文件中添加以下属性: ```yaml server.port=8080 # 添加第二个端口配置 server.additional-ports=9090 ``` 2. 创建一个自定义的`WebServerFactoryCustomizer` bean,并在其中进行端口配置。可以在应用的主类上添加`@Configuration`注解,并定义一个bean方法来创建自定义的`WebServerFactoryCustomizer`。 ```java import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ServerConfig { @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { return (WebServerFactoryCustomizer<ConfigurableWebServerFactory>) factory -> { if (factory instanceof ConfigurableServletWebServerFactory) { // 配置第二个端口 ((ConfigurableServletWebServerFactory) factory).setPort(9090); } }; } } ``` 这里使用了`ConfigurableServletWebServerFactory`来进行配置。通过创建一个自定义的`WebServerFactoryCustomizer` bean,并实现`WebServerFactoryCustomizer<ConfigurableWebServerFactory>`接口,在`customize()`方法中对第二个端口进行配置。 这样配置完成后,你的Spring Boot应用就会同时监听8080和9090两个端口。你可以根据需求进行相应的调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值