How to change Context Path in Spring Boot | ninjasquad
In this quick article, we learn how to change the servlet context path in the Spring Boot application.
Overview
Spring Boot application, by default, serves the content at the root context path (“/”) i.e. localhost:port
Some application requires serving the content from a custom root context path e.g. localhost:port/{app-name}
and have all the Rest controller APIs paths append to it.
Luckily, in Spring Boot, you can change the root context path by just setting a property.
Using Application property
application.properties
Set the following property for Spring Boot 2.x and above version:-
server.servlet.context-path=/app-name
For Spring Boot 1.x, use:-
server.context-path=/app-name
Using Java Config
You have to provide a bean of WebServerFactoryCustomizer
for Spring Boot 2.x and above version:-
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/app-name");
}
For Spring Boot 1.x, provide a bean of EmbeddedServletContainerCustomizer
like this:-
@Bean
public EmbeddedServletContainerCustomizer
embeddedServletContainerCustomizer() {
return container -> container.setContextPath("/app-name");
}
Using Environment Variable
You can also use OS environment variable to set the servlet context path for Spring Boot Application.
Use the following OS environment variable for Spring Boot 2.x and above version:-
UNIX
$ export SERVER_SERVLET_CONTEXT_PATH=/app-name
WINDOWS
> set SERVER_SERVLET_CONTEXT_PATH=/app-name
For Spring Boot 1.x, use:-
UNIX
$ export SERVER_CONTEXT_PATH=/app-name
WINDOWS
> set SERVER_CONTEXT_PATH=/app-name
That is all about this article. Thanks for Reading!
Source: Internet