How to Change the Default Port in Spring Boot

1. Introduction

In this tutorial, You'll learn how to change the 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.

Spring Boot Port Change To Custom or New Port From Default

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.

0 Comments