spring boot

Change The Spring Boot Context Path

Article on how to change spring boot application context path.

In the previous post, we saw how to change the spring boot application’s server port number. We can also change the spring boot application context path easily.

In this article, we will learn different ways to change the application’s context path.

By default, the application’s context path is set to “/“.

We can change the application’s context path in different ways. Following are a few of the methods, to change the application’s context path.

Table of Contents

Using configuration file to change spring boot context path

We can set the spring application’s context path using the server.servlet.context-path property.

application.properties

server.servlet.context-path=/myapp

application.yml

server:
  servlet:
    context-path: /myapp

Using command line arguments to change context path

We can change the context path using the command-line argument during the run command.

java -jar -Dserver.servlet.context-path=/myapp myapp.jar

Change the spring context path programmatically

We can use the WebServerFactoryCustomizer interface to change the application’s context path.

@SpringBootApplication
public class SpringBootTestApplication implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

	public static void main(String[] args) {
		SpringApplication.run(SpringBootTestApplication.class, args);
	}

	@Override
	public void customize(ConfigurableServletWebServerFactory factory) {
		factory.setContextPath("/myapp");
	}
}

Here, as shown above we have to create a configuration class and implement the WebServerFactoryCustomizer interface. Then we need to override the customize() method.

This method accepts a ConfigurableServletWebServerFactory instance as a method parameter and then we use this instance’s setContextPath() method to set the customized context path.

In the above example, we are setting the spring boot application’s context path to /myapp.

Conclusion

In this article, we learned about different methods to change the application’s context path.