Spring Boot Change Context Path
1. Overview
And while, usually, it’s a good idea to prefer convention over configuration, there are cases when we do want to have a custom path.
In this quick tutorial, we’ll cover the different ways of configuring it.
2. Setting the Property
Just like many other configuration options, the context path in Spring Boot can be changed by setting a property, i.e., server.servlet.context-path.
Note that this works for Spring Boot 2.x.
For Boot 1.x, the property is server.context-path.
There are multiple ways of setting this property, let’s look at these one by one.
2.1. Using application.properties / yml
The most straightforward way of changing the context path is to set the property in the application.properties/yml file:
server.servlet.context-path=/baeldung
Instead of putting the properties file in src/main/resources, we can also keep it in the current working directory (outside of the classpath).
2.2. Java System Property
public static void main(String[] args) {
System.setProperty("server.servlet.context-path", "/baeldung");
SpringApplication.run(Application.class, args);
}
2.3. OS Environment Variable
$ export SERVER_SERVLET_CONTEXT_PATH=/baeldung
On Windows, the command to set an environment variable is:
> set SERVER_SERVLET_CONTEXT_PATH=/baeldung
The above environment variable is for Spring Boot 2.x.x, If we have 1.x.x, the variable is SERVER_CONTEXT_PATH.
3. Using Java Config
With Spring Boot 2, we can use WebServerFactoryCustomizer:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/baeldung");
}
With Spring Boot 1, we can create an instance of EmbeddedServletContainerCustomizer:
@Bean
public EmbeddedServletContainerCustomizer
embeddedServletContainerCustomizer() {
return container -> container.setContextPath("/baeldung");
}
4. Priority Order of Configurations
Here’s the priority order in descending order, which Spring Boot uses to select the effective configuration:
-
Java Config
-
Command Line Arguments
-
Java System Properties
-
OS Environment Variables
-
application.properties in Current Directory
-
application.properties in the classpath (src/main/resources or the packaged jar file)