$show=/label

Spring Boot - How to Change Default Port in Spring Application?

SHARE:

A quick guide to change the port for Spring Boot application. Examples to server.port property in application.properties file and yml file. And also from Command Line Arguments, @SpringBootApplication, WebServerFactoryCustomizer

1. Introduction

In this tutorial, You'll learn how to change the default port to new custom port in Spring Boot application.

Spring Boot by default does many auto configurations and provides the ways to customize as per the need.

The most common use case is changing the port of application to the new one. Because by default embedded tomcat is configured with 8080 port. If you already another service that is running on the same port then you can not start a new service on that port. So, you must have to run the application on a different port. 

Changing the port can be done in many possible ways.

Let us see one be one with practical example programs.



2. Changing the Port by using Properties and YML Files


I just created a new Spring Boot application and started on the default tomcat server on port 8080.

application.properties

This is the message from logs saying "Tomcat started on port(s): 8080".
2020-05-06 20:16:17.003  INFO 19737 --- [           main] j.s.S.SpringBootCofigurationsApplication : Starting SpringBootCofigurationsApplication on -MacBook-Pro-2.local with PID 19737

2020-05-06 20:16:17.006  INFO 19737 --- [           main] j.s.S.SpringBootCofigurationsApplication : No active profile set, falling back to default profiles: default

2020-05-06 20:16:17.921  INFO 19737 --- [           main] o.s.b.w.embedded.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] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext

2020-05-06 20:16:18.044  INFO 19737 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 999 ms

2020-05-06 20:16:18.222  INFO 19737 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'

2020-05-06 20:16:18.387  INFO 19737 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''

2020-05-06 20:16:18.391  INFO 19737 --- [           main] j.s.S.SpringBootCofigurationsApplication : Started SpringBootCofigurationsApplication in 1.689 seconds (JVM running for 2.651)

Now to change the port, just add a property in application.properties file as below.

[server.port=9000]

The above property server.port will change the tomcat port to 9000. The properties file will be under the resources folder.

After adding, You need to restart the application to make configurations changes into effect.

Showing only lasts a few lines from the app console. Now default port 8080 changed to 9000

2020-05-06 20:20:05.358  INFO  Initializing ExecutorService 'applicationTaskExecutor'
2020-05-06 20:20:05.500  INFO  Tomcat started on port(s): 9000 (http) with context path ''
2020-05-06 20:20:05.504  INFO  Started SpringBootCofigurationsApplication in 1.369 seconds (JVM running for 2.007)

application.yml


Additional to the application.properties files, there is also one more file that will be scanned by spring boot automatically under the src/main/resources folder.


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

But if the port property is present in both files then application.properties file port will be considered with the highest precedence.

3. Environment Specific Ports in Spring Boot


As similar to the application.properties, you can have a different properties file for each environment such as dev, sit, QA, and prod.

application-dev.properties

server.port= 9008

application-qa.properties

server.port= 8008

These files are most useful to deploy the application in multiple environments without any changes for every change or deployment.

4. Changing Port Programmatically


If you do not have access to the properties file then you can do achieve this using on the @SpringBootApplication annotation class or custom embedded tomcat server settings.

4.1 @SpringBootApplication Class Level


Use the same property "server.port" to set the custom port. The below program sets to 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 Using WebServerFactoryCustomizer Interface


Implement any class with Interface WebServerFactoryCustomizer<ConfigurableWebServerFactory> and implements customize() method to set the port using setPort() method.

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);
    }
}




If you receive this error make sure you are not calling the SpringApplication.run() twice.

ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class 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

2020-05-06 21:26:09.907  INFO 21555 --- [           main] o.s.s.concurrent.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 'debug' enabled.

2020-05-06 21:26:09.923 ERROR 21555 --- [           main] o.s.boot.SpringApplication               : Application run failed



org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springApplicationAdminRegistrar' defined in class 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

 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. Using Command-Line Arguments


If you are not a developer and do the only deployment. If you are going to start the application as standalone then you can run java -jar command as below by specifying the --server,port flag.

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


or you can use as VM arguments from eclipse or Intelleji or any IDE.

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

6. Order of Evaluation (Precedence)


You should be very careful if you configure in multiple ways unknowingly it may run on the different port and little difficult to find out also.

Here is the list of precedence from high to low priority.

  • Embedded server configuration - WebServerFactoryCustomizer Interface
  • Command-line arguments
  • Property files
  • main @SpringBootApplication configuration

7.Conclusion


In this article, You've seen how many ways port can be changed to custom port from the default port in Spring Boot application.

In the repo, all configs are commented on. Please uncomment the needed one for you.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Spring Boot - How to Change Default Port in Spring Application?
Spring Boot - How to Change Default Port in Spring Application?
A quick guide to change the port for Spring Boot application. Examples to server.port property in application.properties file and yml file. And also from Command Line Arguments, @SpringBootApplication, WebServerFactoryCustomizer
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/spring-boot-change-port.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/spring-boot-change-port.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content