By default, Spring boot applications are accessed by context path “/” which is the default for embedded servers i.e. we can access the application directly at http://localhost:8080/
.
But in production, we will deploy the application under some context root – so that we can refer to the URLs for other places. Also, it is desirable to configure security and there we will need the application’s context root.
1. Change Context Root in application.properties
We can change the context root path using the property server.servlet.context-path
in the properties file.
server.servlet.context-path=/MyApp
For Boot 1.x, the property was server.context-path.
2. Using Java Configuration
We can customize the bean WebServerFactoryCustomizer as it gets a callback with the server factory before the server itself is started. We can use it to change application context path, port, address, error pages, etc.
Add the following bean definition in a @Configuration annotated class.
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/MyApp");
}
3. Using Command-line Argument
If the application is distributed as an uber jar then we may consider this option as well. It gives the liberty to deploy the same application with different context paths as per requirements, if any,
java -jar --server.servlet.context-path=/MyApp spring-boot-demo.jar
Let me know if you know of any other way to accomplish this change in spring boot change context path.
Happy Learning !!
Comments