By default, Spring boot serves content on the root context path /
. Itโs usually a good idea to prefer convention over configuration, but sometimes we want to configure a custom path to match our application needs.
Like many other properties in Spring boot, the context path can be changed by setting a property, server.servlet.context-path
. (This configuration works for spring boot 2.x).
Anyway, there are multiple ways to set up this property, letโs look at them below.
Using Java System Property
We can set the context path as a Java system property before the context is even initialized:
public static void main(String[] args) {
System.setProperty("server.servlet.context-path", "/demo-post");
SpringApplication.run(Application.class, args);
}
Using application.properties
You can also change the context path property in the ย application.properties
file:
server.servlet.context-path=/demo-post
Using Environment Variable
Spring Boot can also rely on OS environment variables. On each system below, we can write:
# On Unix based systems we can write:
$ export SERVER_SERVLET_CONTEXT_PATH=/demo-post
# On Windows, the command to set an environment variable is:
> set SERVER_SERVLET_CONTEXT_PATH=/demo-post
The above environment variable is for Spring Boot 2.x**.** ย If you use the 1.x.x version, the variable is SERVER_CONTEXT_PATH
.
Using command line arguments
We can also set the properties dynamically via command line arguments as well:
$ java -jar app.jar --server.servlet.context-path=/demo-post
Wrap up
In this article, we have covered different way to set up a context-path of a spring boot application. They are many options to configure this property, so consider this list of priority order, which spring boot uses to select the effective configuration:
- Command Line Arguments
- Java System Properties
- OS Environment Variables
- application.properties in the classpath (src/main/resources)
๐. Similar posts
Simplifying Layouts With React Fragments
18 Jan 2025
Stop Installing Node Modules on Your Docker Host - Install Them in the Container Instead
14 Jan 2025
An Easy to Understand React Component Introduction for Beginners
14 Jan 2025