Spring Boot Change Port
The Spring Boot, you can change the default port on which your application runs by modifying the application.properties
or application.yml
configuration file. By default, Spring Boot applications typically run on port 8080, but you can specify a different port of your choice. Here’s how to do it:
Using application.properties
:
- Create or open the
application.properties
file in thesrc/main/resources
directory of your Spring Boot project. - Add the following property to change the port to your desired value (e.g., port 8081):
server.port=8081
Replace 8081
with the port number you want to use.
Using application.yml
:
- Create or open the
application.yml
file in thesrc/main/resources
directory of your Spring Boot project. - Add the following configuration to change the port to your desired value (e.g., port 8081):
server:
port: 8081
Replace 8081
with the port number you want to use.
Command Line Argument:
You can also change the port when running your Spring Boot application from the command line by specifying the server.port
property as a command-line argument. For example:
java -jar my-application.jar --server.port=8081
This will override the port configuration specified in the application.properties
or application.yml
file.
Programmatic Configuration:
If you need to change the port programmatically in your Spring Boot application, you can do so by modifying the application’s configuration class. For example:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.boot.context.properties.ConfigurationProperties;
@SpringBootApplication
public class MyApplication extends SpringBootServletInitializer {
@Bean
@ConfigurationProperties(prefix = "server")
public ServerProperties serverProperties() {
return new ServerProperties();
}
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
In this example, you can set the server port programmatically by modifying the ServerProperties
bean.
After making the necessary changes, save the configuration file, and when you run your Spring Boot application, it will listen on the new port that you have specified.