by BehindJava

How to add context path to Spring Boot application

Home » java » How to add context path to Spring Boot application

In this tutorial we are going to learn about adding the context path to Spring Boot application.

If you are using Spring Boot, then you don’t have to configure the server properties via Bean initializing.

Instead, if one functionality is available for basic configuration, then it can be set in a “properties” file called application, which should reside under src\main\resources in your application structure. The “properties” file is available in two formats



The way you specify or set the configurations differs from one format to the other.

In your specific case, if you decide to use the extension .properties, then you would have a file called under src\main\resources with the following configuration settings

server.port = 8080
server.contextPath = /context-path

OTOH, if you decide to use the .yml extension (i.e. application.yml), you would need to set the configurations using the following format (i.e. YAML):

    port: 8080
    contextPath: /context-path

You can do it by adding the port and contextpath easily to add the configuration in src\main\resources .properties file and also .yml file

application.porperties file configuration

server.port = 8084
server.contextPath = /context-path

application.yml file configuration

port: 8084
contextPath: /context-path

We can also change it programmatically in spring boot.

public class ServerPortCustomizer implements     WebServerFactoryCustomizer<EmbeddedServletContainerCustomizer > {

public void customize(EmbeddedServletContainerCustomizer factory) {

We can also add an other way

public class MyApplication {
public static void main(String[] args) {SpringApplication application =     new pringApplication(MyApplication.class);
    Map<String, Object> map = new HashMap<>();
    map.put("server.servlet.context-path", "/context-path");
    map.put("server.port", "808");

using java command spring boot 1.X

java -jar my-app.jar --server.contextPath=/spring-boot-app     --server.port=8585 

using java command spring boot 2.X

java -jar my-app.jar --server.servlet.context-path=/spring-boot-app --server.port=8585