Out of the box, Spring boot applications are accessed through the default context path “/” i.e. you can access the application directly at http://localhost:PORT/
. In this tutorial we will learn how to change the default root Web context of a Spring Boot application. As you will see, Spring boot is quite flexible and provide you multiple options to configure applications context root path.
1) Change context root from application.properties file
This file is located in the resources folder of your project. Out of the box it’s empty:
In order to change the context root path or the default Tomcat port is pretty simple:
##### Default server path ######### server.port= 8080 ##### Context root path ######## server.contextPath=/mycontext |
2) Implement EmbeddedServletContainerCustomizer interface
It is also possible to change programmatically the Web context through the EmbeddedServletContainerCustomizer interface which is used for customizing auto-configured embedded servlet containers. Any beans of this type will get a callback with the container factory before the container itself is started, so you can set the port, address, error pages etc.
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; import org.springframework.stereotype.Component; @Component public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer { @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(8080); container.setContextPath("/home"); } }
3) Use the command line to change the Web Context
Last but not least, it is possible to vary the default Web context using the command line, passing it as option:
java -jar -Dserver.contextPath=/home spring-boot-demo.jar |