HomeJavaChange Context Path in Spring Boot Application

Change Context Path in Spring Boot Application

The default context path of the Spring Boot application is the root context path(“/”). Usually, conventions are preferred over configuration; however, there may be cases when we want to have a custom context path of our application. In this journal entry, we will be looking at how to change context path in Spring Boot application.

Spring Boot applications provide multiple configuration options properties. To change the context path we can change the property value of server.servlet.context-path.

Let’s have a look at different ways to configure the context path.

#1 Using application.properties/yml file

This is the most straightforward way of changing the context path. You need to set the property in the application.properties/yml file:


The properties file can in src/main/resources folder, or we can keep the same in a different directory (outside of the classpath) and use @PropertySource annotation to pass in the path of the properties file.

#2 Using Java System property

We can use the Java System property to set the context path even before the context is initialized.

public static void main(String[] args) {
    System.setProperty("server.servlet.context-path", "/developersjournal");
    SpringApplication.run(SpringBootApplication.class, args);

#3 Using OS Environment Variables

Spring Boot applications can also rely on OS environment variables. Let’s have a look at setting up OS Environment Variables:

In Unix-based OS

export SERVER_SERVLET_CONTEXT_PATH=/developersjournal

In Windows-based OS

set SERVER_SERVLET_CONTEXT_PATH=/developersjournal

#4 Using Command Line arguments

We can use command-line arguments also to set the context path dynamically.

java -jar SpringBootApplication.jar --server.servlet.context-path=/developersjournal

#5 Using Java Configuration Bean

The context path can also be set by populating the bean factory with a configuration bean. For this, we can use WebServerFactoryCustomizer method.

public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
  webServerFactoryCustomizer() {
    return factory -> factory.setContextPath("/developersjournal");

Order of Priority

With these options, we may end up using more than one configuration settings for the context path of the application. To understand how Spring Boot selects the effective configuration, given below is the priority order in descending order.

  1. Java Configuration Bean
  2. Command Line Arguments
  3. Java System Properties
  4. OS Environment Variables
  5. application.properties in a different directory.
  6. application.properties in the classpath (src/main/resources)


Please enter your comment!
Please enter your name here

Most Popular