Languages
[Edit]
EN

Spring Boot 2 - change default application port from source code

6 points
Created by:
Marcin
2477

To change change default application port from source code with Spring Boot 2 it is necessary to create own bean that overrides default port configuration. This article shows how to do it.

Notes:

  • read this article to see different methods how to change default port with Spring Boot,
  • read this article to see the exact place where to keep bean¬†configurations.

Spring Boot 2.x.x - web server factory bean

In this approach webServerFactory() method that returns ConfigurableServletWebServerFactory object is used.

ServerConfig.java file:

package com.dirask.examples;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ServerConfig {

    @Bean
    public ConfigurableServletWebServerFactory webServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();

        factory.addConnectorCustomizers(connector -> {
            connector.setPort(80);
        });

        return factory;
    }
}

ServerConfig.java file location:

Server port with ServerConfig.java file location - Spring Boot 2.x.x + IntelliJ
Server port with ServerConfig.java file location - Spring Boot 2.x.x + IntelliJ

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.