How to change the port of the server used by spring boot

The port used by spring boot for the webserver can be configured using server.port parameter.

        SpringApplication app = new SpringApplication(StaticGenerator3.class);
        app.setWebEnvironment(true);

        Properties props = new Properties();
        props.put( "server.port" , "9090");
        app.setDefaultProperties(props);

The following error can be returned if springboot tries to start but the server port is already used. This can be caused by another application running on the same port or if the application is still running.
The Tomcat connector configured to listen on port 8080 failed to start. The port may already be in use or the connector may be misconfigured. Verify the connector's configuration, identify and stop any process that's listening on port 8080, or configure this application to listen on another port.

1- Create the following java file:

The code creates a spring boot application running on port 9090. The property server.port is defined using the Properties Object and passed to the default properties of the application. The web environment variable needs to be set to true, so spring starts the web server. The banner is set to off, so no splash screen is displayed.

import java.util.Properties;

import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@EnableJpaRepositories
@EnableAutoConfiguration
public class StaticGenerator3 implements CommandLineRunner {

    
    public static void main(String[] args) throws Exception {

        //disabled banner, don't want to see the spring logo
        SpringApplication app = new SpringApplication(StaticGenerator3.class);
        app.setBannerMode(Banner.Mode.OFF);
        app.setWebEnvironment(true);

        Properties props = new Properties();
        props.put( "server.port" , "9090");
        app.setDefaultProperties(props);
        
        // Call the run method
        app.run(args);

    }

    @Override
    public void run(String... args) throws Exception {
	    // Put your logic here.

    }
}

References:

Java 8
Spring Boot

Share this article:

Recent Comments