Spring Boot Change Context Path

In this article, we will look in to the options to change context path in Spring Boot application. By default, Spring Boot server the context from the root ("/"). Let’s look at some options to change the context path in Spring Boot.

 

1. Change Context Path using Properties file

The application.properties file provides many configurations including the option to change the application context for your application. To change the context path use the following properties in the application.properties file:

Spring Boot 1.0
server.contextPath=/javadevjournal
#### Spring Boot 2.0 Configurations ####
server.servlet.contextPath=/javadevjournal

 

2. Using Java System Property

Second alternate is to use the Java system property to set the context path for your Spring Boot application.

System.setProperty("server.servlet.context-path","/javadevjournal")

 

3. Command Line Arguments

Spring Boot also provides an option to pass the context information as part of the command line arguments.

$ java -jar javadevjournal.jar --server.servlet.context-path=/javadevjournal

 

4. Using Java Configurations

Spring Boot 1.0 and 2.0 provides a different way to configure the context using Java configurations.With Spring Boot 2, we can use WebServerFactoryCustomizer.

@Component
public class AppCustomizer implements WebServerFactoryCustomizer {

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        factory.setContextPath("/javadevjournal");
    }
}

For Spring Boot 1.0, we can create an instance of EmbeddedServletContainerCustomizer:

@Component
public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer {
 
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {

        container.setPort(8080);
        container.setContextPath("/home"); 
    }
}

 

Summary

In this article, we saw a different way to change context path in Spring Boot application.The source code for this post is available over GitHub.