1. Introduction
In this tutorial, We'll be learning how to set a base path in a new spring boot application? And also how the existing context path can be changed to new values in different ways.
2. Setting Property in application.properties
Older and new versions of spring boot support in doing our own base path using configurations file that is application.properties.
Spring Boot 1.x:
spring.data.rest.basePath=/api/v1
Spring Boot 2.x:
server.servlet.context-path=/api/v1
The main difference is path is called a base path in 1.x and context path in 2.x but the meaning of both is the same.
Both of these change to proceeding with "/api/v1".
3. Using Java Property Using System
You can use the System.setProperty() method to set the base path.
public static void main(String[] args) { System.setProperty("server.servlet.context-path", "/api/v1"); SpringApplication.run(Application.class, args); }
4. Using OS Variables
Mac OS X: Open the terminal and run the command.
$ export SERVER_SERVLET_CONTEXT_PATH=/api/v1
Windows: Run the below command in command prompt.
set SERVER_SERVLET_CONTEXT_PATH=/api/v1
5. Java Command Line Argument
You can set the base path when starting up the spring boot application as below.
$ java -jar app.jar --server.servlet.context-path=/api/v1
6. Using RepositoryRestConfigurer
This works spring boot 1.1 before versions and even if you are not using Spring Boot.
@Configuration class CustomRestMvcConfiguration { @Bean public RepositoryRestConfigurer repositoryRestConfigurer() { return new RepositoryRestConfigurerAdapter() { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.setBasePath("/api/v1"); } }; } }
7. Spring Boot 2.x WebServerFactoryCustomizer
@Bean public WebServerFactoryCustomizerwebServerFactoryCustomizer() { WebServerFactoryCustomizer customizer = factory -> factory .setContextPath("/api/v1"); logger.info("Setting up the custom base path "); return customizer; }
8. Conclusion
In this article, We have seen how to set the context path in spring boot applications.
Below are the priority list from high to low. Always Java config will be in higher precedence.
Java Config - Is the highest priority
Command Line Args - 2nd
Java System Properties - 3rd
OS Level Environment Variables - 4th
application.properties in Current Directory - 5th
application.properties in the classpath (src/main/resources or the packaged jar file) - Least priority
GitHub Java Config
GitHub properties file
No comments:
Post a Comment
Please do not add any spam links in the comments section.