When spring boot application starts, the embedded server such as Tomcat starts with a default port. The embedded tomcat starts with 8080 port as default. There are many ways to change default server port.
Using Property File (.properties/.yml)
To change server port using property file, we need to configure server.port property.
a. Using application.properties in classpath such as src\main\resources\application.properties
server.port = 8585
The server will start with 8585 port. To get random server port, assign 0 to the property.
server.port = 0
Now spring boot will start the server on a port that is not being used currently by any server in the system.
b. Using application.yml in classpath such as src\main\resources\application.yml.
server:
port: 8585
Server will start with 8585 port.
For random port, assign 0.
server:
port: 0
Using java Command with --server.port or -Dserver.port
Suppose we have an executable JAR named as my-app.jar, then while starting spring boot application using java command we can use the argument as follows.
Using --server.port
java -jar my-app.jar --server.port=8585
Using -Dserver.port
java -jar -Dserver.port=8585 my-app.jar
Server will start with 8585 port.
Using java Command with --port or -Dport in Short
To make --server.port and -Dserver.port in short, we can remove server keyword and make it any short keyword such as --port and -Dport. We can use any short keyword. Here we are using port as short keyword. To achieve it we need to configure placeholder in property file as follows.
Using application.properties
server.port=${port:8282}
Using application.yml
server:
port: ${port:8282}
If we do not pass the port as the argument then by default server will start with 8282. If we want a different port, then we need to pass desired port in argument as follows. Suppose we have an executable JAR named as my-app.jar.
Using --port
java -jar my-app.jar --port=8585
Using -Dport
java -jar -Dport=8585 my-app.jar
Server will start with 8585 port.
Using SERVER_PORT with SpringApplication Programmatically
SpringApplication has a method as setDefaultProperties() that is used to change spring boot default properties. Suppose we want to change default port then we need to create a Map and put a port with SERVER_PORT key. Find the example.
MyApplication.java
package com.humoyun;
import java.util.HashMap;
import java.util.Map;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(MyApplication.class);
Map<String, Object> map = new HashMap<>();
map.put("SERVER_PORT", "8585");
application.setDefaultProperties(map);
application.run(args);
}
}
Spring boot will start the server with 8585 port.