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
I hope you enjoyed reading this, and I'm curious to hear if this tutorial helped you. Please let me know your thoughts below in the comments. Don't forget to subscribe to my newsletter to avoid missing my upcoming blog posts.
You can also find me here LinkedIn • Twitter • GitHub or Medium
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)