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 !!

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Comments are closed for this article!

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.