In previous post, we saw how to change spring boot application’s server port number. In this article, we will learn different ways to change application’s context path.

Customize Spring Boot Application Context Path

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

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

Using configuration file

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

application.properties

server.servlet.context-path=/myapp

application.yml

server:
  servlet:
    context-path: /myapp

Using command line arguments

We can change context path by passing command line argument during run command.

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

Context path programmatic customization

We can use WebServerFactoryCustomizer interface to change spring boot 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");
	}
}

Conclusion

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

Happy learning 🙂 🙂

You may also interested in