How to add context path to Spring Boot application
In this tutorial we are going to learn about adding the context path to Spring Boot application.
If you are using Spring Boot, then you don’t have to configure the server properties via Bean initializing.
Instead, if one functionality is available for basic configuration, then it can be set in a “properties” file called application, which should reside under src\main\resources in your application structure. The “properties” file is available in two formats
.yml
.properties
The way you specify or set the configurations differs from one format to the other.
In your specific case, if you decide to use the extension .properties, then you would have a file called application.properties under src\main\resources with the following configuration settings
server.port = 8080
server.contextPath = /context-path
OTOH, if you decide to use the .yml extension (i.e. application.yml), you would need to set the configurations using the following format (i.e. YAML):
server:
port: 8080
contextPath: /context-path
You can do it by adding the port and contextpath easily to add the configuration in src\main\resources .properties file and also .yml file
application.porperties file configuration
server.port = 8084
server.contextPath = /context-path
application.yml file configuration
server:
port: 8084
contextPath: /context-path
We can also change it programmatically in spring boot.
@Component
public class ServerPortCustomizer implements WebServerFactoryCustomizer<EmbeddedServletContainerCustomizer > {
@Override
public void customize(EmbeddedServletContainerCustomizer factory) {
factory.setContextPath("/context-path");
factory.setPort(8084);
}
}
We can also add an other way
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {SpringApplication application = new pringApplication(MyApplication.class);
Map<String, Object> map = new HashMap<>();
map.put("server.servlet.context-path", "/context-path");
map.put("server.port", "808");
application.setDefaultProperties(map);
application.run(args);
}
}
using java command spring boot 1.X
java -jar my-app.jar --server.contextPath=/spring-boot-app --server.port=8585
using java command spring boot 2.X
java -jar my-app.jar --server.servlet.context-path=/spring-boot-app --server.port=8585