Spring Boot Essentials: Change the Context Path

Overview

The default context path in Spring Boot is "/".

This article will cover the different ways we can change the context path.

Properties File (recommended)

Setting the context path via the application.properties file is the recommended method since it externalizes the configuration.    

application.properties

Spring Boot 1.x

server.contextPath=/myapp

Spring Boot 2.x

server.servlet.context-path=/myapp

Spring Component

The alternative approach is to create a customizer component to configure the context path. 

This approach will override the setting in a properties file.

Spring Boot 1.x

Below, we create a class that implements the EmbeddedServletContainerCustomizer interface:

package com.codebyamir.demo;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;
 
@Component
public class Customizer implements EmbeddedServletContainerCustomizer {

  @Override
  public void customize(ConfigurableEmbeddedServletContainer server) {
    server.setContextPath("/myapp");
  }
}

Spring Boot 2.x

Things have changed a bit in Spring Boot 2.0 so we now implement the WebServerFactoryCustomizer interface:

package com.codebyamir.demo;

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

@Component
public class Customizer implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

  @Override
  public void customize(ConfigurableServletWebServerFactory server) {
    server.setContextPath("/myapp");
  }
}