This post will discuss how to set a context path in a Spring Boot application.

By default, Spring Boot serves content on the root context path (/). We can set the context path of the Spring Boot application in a properties file called application, which is available in two formats – .properties and .yml.

1. Property file

In Spring Boot, we can set the context path in application.properties, as shown in the following example:

 
Note that with the release of Spring Boot 2.0.0, the context path property has been changed to the following:

2. YAML file

We can also store external properties in a YAML file, application.yml, which is a superset of JSON. The preceding example corresponds to the following YAML file:

 
For Spring Boot 2.0.0 and above:

 
Note that both application.properties and application.yml can be placed in four pre-determined locations:

  1. root of the classpath (src\main\resources)
  2. current directory
  3. package /config in classpath
  4. /config subdirectory of the current directory

 
We can also use Java System Property, OS environment variables, and command-line arguments to set the Spring Boot application context path.

1. Java System property

We can set server.servlet.context-path as System property inside the main method, as shown below:

2. Define OS environment variable

We can also use SERVER_SERVLET_CONTEXT_PATH as an OS environment variable in Unix/windows. This works since Spring Boot uses some relaxed rules for binding Environment properties to @ConfigurationProperties beans.

 
1. Windows

 
2. UNIX

 
We can also configure the context path programmatically:

 
1. Before Spring Boot 2, we can use the EmbeddedServletContainerCustomizer interface.

 
2. With Spring Boot 2, the EmbeddedServletContainerCustomizer interface is replaced by WebServerFactoryCustomizer,

That’s all about setting the context path in a Spring Boot application.