Spring Boot端口从默认更改为自定义或新端口

更改Spring Boot应用程序端口的快速指南。 application.properties文件和yml文件中的server.port属性的示例。 以及从命令行参数@ SpringBootApplication,WebServerFactoryCustomizer

1.简介

在本教程中,您将学习如何在Spring Boot应用程序中更改端口。

默认情况下,Spring Boot会执行许多自动配置,并提供了根据需要进行自定义的方法。

最常见的用例是将应用程序端口更改为新端口。 因为默认情况下, 嵌入式tomcat配置有8080端口。 如果您已经在同一端口上运行了另一个服务,则无法在该端口上启动新服务。 因此,您必须在其他端口上运行该应用程序。

可以通过许多可能的方式更改端口。

让我们看一看实用示例程序。

2.通过使用属性和YML文件更改端口

我刚刚创建了一个新的Spring Boot应用程序,并在端口8080上的默认tomcat服务器上启动。

application.properties

这是来自日志的消息,内容为“ Tomcat在端口8080上启动”。

 2020-05-06 20:16:17.003 INFO 19737 --- [      main] jsSSpringBootCofigurationsApplication : Starting SpringBootCofigurationsApplication on -MacBook-Pro-2.local with PID 19737  2020-05-06 20:16:17.006 INFO 19737 --- [      main] jsSSpringBootCofigurationsApplication : No active profile set, falling back to default profiles: default  2020-05-06 20:16:17.921 INFO 19737 --- [      main] osbwembedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)  2020-05-06 20:16:17.932 INFO 19737 --- [      main] o.apache.catalina.core.StandardService  : Starting service [Tomcat]  2020-05-06 20:16:17.933 INFO 19737 --- [      main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]  2020-05-06 20:16:18.044 INFO 19737 --- [      main] oaccC[Tomcat].[localhost].[/]    : Initializing Spring embedded WebApplicationContext  2020-05-06 20:16:18.044 INFO 19737 --- [      main] osweb.context.ContextLoader      : Root WebApplicationContext: initialization completed in 999 ms  2020-05-06 20:16:18.222 INFO 19737 --- [      main] ossconcurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'  2020-05-06 20:16:18.387 INFO 19737 --- [      main] osbwembedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''  2020-05-06 20:16:18.391 INFO 19737 --- [      main] jsSSpringBootCofigurationsApplication : Started SpringBootCofigurationsApplication in 1.689 seconds (JVM running for 2.651) 

现在要更改端口,只需在application.properties文件中添加一个属性,如下所示。


[server.port = 9000]

上面的属性server.port会将tomcat端口更改为9000。属性文件将位于resources文件夹下。

添加后,您需要重新启动应用程序以使配置更改生效。

从应用程序控制台仅显示最后几行。 现在默认端口8080更改为9000

2020-05-06 20:20:05.358信息初始化ExecutorService'applicationTaskExecutor'
2020-05-06 20:20:05.500信息Tomcat在具有上下文路径“”的端口:9000 (http)上启动 2020-05-06 20:20:05.504信息在1.369秒内启动了SpringBootCofigurationsApplication(JVM运行2.007)

application.yml

除了application.properties文件之外,还有一个其他文件,该文件将由spring boot自动扫描在src / main / resources文件夹下。

 application: 
   name: spring-boot-configurations  server: 
   port: 9006 

但是,如果两个文件中都存在端口属性,则application.properties文件端口将被认为具有最高优先级。

3. Spring Boot中的特定于环境的端口

与application.properties类似,对于每个环境(例如dev,sit,QA和prod),您可以具有不同的属性文件。

application-dev.properties

server.port = 9008

application-qa.properties

server.port = 8008

这些文件对于在多个环境中部署应用程序而对每次更改或部署都没有任何更改最有用。

4.以编程方式更改端口

如果您无权访问属性文件,则可以使用@SpringBootApplication批注类或自定义嵌入式tomcat服务器设置来实现

4.1 @SpringBootApplication类级别

使用相同的属性“ server.port”设置自定义端口。 下面的程序设置为9009。

 package com.javaprogramto.springboot.SpringBootCofigurations;  import org.springframework.boot.SpringApplication;  import org.springframework.boot.autoconfigure.SpringBootApplication;  import java.util.HashMap;  import java.util.Map;  @SpringBootApplication  public class SpringBootCofigurationsApplication { 
     public static void main(String[] args) { 
        // SpringApplication.run(SpringBootCofigurationsApplication.class, args); 
         SpringApplication app = new SpringApplication(SpringBootCofigurationsApplication. class ); 
         Map<String, Object> customConfig = new HashMap<>(); 
         customConfig.put( "server.port" , "9009" ); 
         app.setDefaultProperties(customConfig); 
         app.run(args); 
     }  } 

4.2使用WebServerFactoryCustomizer界面

使用Interface WebServerFactoryCustomizer <ConfigurableWebServerFactory>实现任何类,并实现customset()方法以使用setPort()方法设置端口。

 package com.javaprogramto.springboot.SpringBootCofigurations;  import org.springframework.boot.web.server.ConfigurableWebServerFactory;  import org.springframework.boot.web.server.WebServerFactoryCustomizer;  import org.springframework.stereotype.Component;  @Componentpublic class CustomEmbededPortChange implements WebServerFactoryCustomizer<ConfigurableWebServerFactory> { 
     @Override  public void customize(ConfigurableWebServerFactory factory) { 
         factory.setPort(8086); 
     }  } 

如果收到此错误,请确保没有两次调用SpringApplication.run()。

 ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name defined in class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration. defined in ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration. class ]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication ]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication  2020-05-06 21:26:09.907 INFO 21555 --- [      main] ossconcurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'  2020-05-06 21:26:09.908 INFO 21555 --- [      main] o.apache.catalina.core.StandardService  : Stopping service [Tomcat]  2020-05-06 21:26:09.915 INFO 21555 --- [      main] ConditionEvaluationReportLoggingListener :  Error starting ApplicationContext. To display the conditions report re-run your application with Error starting ApplicationContext. To display the conditions report re-run your application with enabled. 'debug' Error starting ApplicationContext. To display the conditions report re-run your application with enabled.  2020-05-06 21:26:09.923 ERROR 21555 --- [      main] osboot.SpringApplication        : Application run failed  org.springframework.beans.factory.BeanCreationException: Error creating bean with name class path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration. defined in org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' org.springframework.beans.factory.BeanCreationException: Error creating bean with name path resource [org/springframework/boot/autoconfigure/admin/SpringApplicationAdminJmxAutoConfiguration. class ]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication ]: Invocation of init method failed; nested exception is javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication 
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:882) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] 
  at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] 
  at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] 
  at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] 
  at com.javaprogramto.springboot.SpringBootCofigurations.SpringBootCofigurationsApplication.main(SpringBootCofigurationsApplication.java:24) ~[classes/:na]  Caused by: javax.management.InstanceAlreadyExistsException: org.springframework.boot:type=Admin,name=SpringApplication 
  at java.management/com.sun.jmx.mbeanserver.Repository.addMBean(Repository.java:436) ~[na:na] 
  at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerWithRepository(DefaultMBeanServerInterceptor.java:1855) ~[na:na] 
  at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerDynamicMBean(DefaultMBeanServerInterceptor.java:955) ~[na:na] 
  at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerObject(DefaultMBeanServerInterceptor.java:890) ~[na:na] 
  at java.management/com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.registerMBean(DefaultMBeanServerInterceptor.java:320) ~[na:na] 
  at java.management/com.sun.jmx.mbeanserver.JmxMBeanServer.registerMBean(JmxMBeanServer.java:522) ~[na:na] 
  at org.springframework.boot.admin.SpringApplicationAdminMXBeanRegistrar.afterPropertiesSet(SpringApplicationAdminMXBeanRegistrar.java:129) ~[spring-boot-2.2.6.RELEASE.jar:2.2.6.RELEASE] 
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1855) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1792) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE] 
  ... 14 common frames omitted 

5.使用命令行参数

如果您不是开发人员,则只进行部署。 如果要独立启动应用程序,则可以通过指定–server,port标志如下运行java -jar命令。

java -jar Spring-Boot-Cofigurations-0.0.1-SNAPSHOT.jar --server.port=9099

或者您可以将其用作eclipse或Intelleji或任何IDE的VM参数。

java -jar -Dserver.port=9099 Spring-Boot-Cofigurations-0.0.1-SNAPSHOT.jar

6.评估顺序(优先级)

如果您在不知不觉中以多种方式进行配置,则应非常小心,因为它可能在不同的端口上运行,并且也很难发现。

这是从高优先级到低优先级的列表。

  • 嵌入式服务器配置– WebServerFactoryCustomizer接口
  • 命令行参数
  • 属性文件
  • @SpringBootApplication主要配置

7,结论

在本文中,您已经了解了从Spring Boot应用程序中的默认端口将端口更改为自定义端口的方法。

在仓库中,所有配置均已注释。 请为您取消注释所需的一个。

本文显示的所有代码都在GitHub上。

您可以直接下载该项目,并且可以在本地运行而没有任何错误。

如果您有任何疑问,请在评论部分中发布。

翻译自: https://www.javacodegeeks.com/2020/05/spring-boot-port-change-to-custom-or-new-port-from-default.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值