Spring Boot – Changing Context Path

By default, Spring boot applications are accessed by context path “/” which is default for embedded servers i.e. we can access the application directly at http://localhost:PORT/.

But in production, we will deploy the application under some context root – so that we can refer the URLs for other places. Also, it is desirable to configure security and there we will need application’s context root.

1. Change context root in application.properties

We can change context root path using simple entry in properties file.

### Spring boot 1.x #########
server.contextPath=/ClientApp

### Spring boot 2.x #########
server.servlet.context-path=/ClientApp

2. Java Config

In Spring boot 2.x, we can customize the bean WebServerFactoryCustomizer. We can use it to change application context path, port, address, error pages etc.

@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
   webServerFactoryCustomizer() {
       return factory -> factory.setContextPath("/ClientApp");
}

In Spring boot 1.x, EmbeddedServletContainerCustomizer interface is used for customizing auto-configured embedded servlet containers.

@Component
public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {

		container.setContextPath("/ClientApp");

	}
}

3. Application argument

If the application is built as uber jar, we may consider this option as well.

java -jar -Dserver.servlet.context-path=/ClientApp spring-boot-demo.jar

Let me know if you know any other way to accomplish this change in spring boot change context path.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “Spring Boot – Changing Context Path”

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.