写在前面
今天需要在一台服务器上同时部署多个相同的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) {
}
}