How to Change the default port in Spring Boot

In previous post we have created spring boot example . Now in this tutorial we will learn how to change port in spring boot . Spring boot default port is 8080 . We can do port configuration for spring boot application port and change it . This port configuration is important when you have multiple application but have only one machine . Your all spring boot application port will 8080 then you can run only one application on this port . If you want to run other spring boot application on same machine then you have to change port of other spring boot application to other port (except 8080). It is a nice guide for spring boot change port using different option as discuss below .

1. Change port in Spring Boot using Properties Files

We can change spring boot default port by port configuration in properties or yml file as below. For this we use server.port key for changing port value in spring boot . In this example we change port in spring boot  from port 8080 to port 8082 . Now our spring boot application will use port 8082 instead of 8080.

Set server.port property in application.properties file.

server.port = 8082

Set server port property in application.yml file

server:
port: 8082

2. Change Port in Spring Boot By Programmatic

We can change spring boot application port by programmatic. If we want to spring boot change port using programmatic then we have to implements WebServerFactoryCustomizer interface . We can set the port, address, error pages etc by  WebServerFactoryCustomizer interface . In this example we change spring boot server port 8080 to port 8082 . Now spring boot application will use port 8082 .

package com.jp.helloWorld.config;

import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;


@Component
public class CustomizationPort implements WebServerFactoryCustomizer
 < ConfigurableServletWebServerFactory > {

	public void customize(ConfigurableServletWebServerFactory server) {
		server.setPort(8082);
		}
	
}

3.  Change Port in Spring Boot Using Command Line Argument

In this method we change spring boot application port by command line argument .  We also have the option to set the port while starting our application. This is done by passing the argument through the command line.

java -jar -Dserver.port=8082 hello-spring-boot.jar

In this tutorial we have learned how to change port in spring boot or port configuration for spring boot application . It is good tutorial for spring boot change port using different methods .

Leave a Reply

Your email address will not be published. Required fields are marked *

35 − = 32