Spring Boot – 更改上下文路径
原文: https://howtodoinjava.com/spring-boot/change-application-root-context-path/
默认情况下,Spring 运行应用程序是通过上下文路径/
访问的,这是嵌入式服务器的默认路径,即我们可以通过http://localhost:PORT/
直接访问该应用程序。
但是在生产中,我们将在某个上下文根目录下部署该应用程序 - 以便我们可以引用其他地方的 URL。 另外,还需要配置安全性,然后我们将需要应用程序的上下文根。
1. 在application.properties
中更改上下文根
我们可以使用属性文件中的简单条目来更改上下文根路径。
application.properties
### Spring boot 1.x #########
server.contextPath=/ClientApp
### Spring boot 2.x #########
server.servlet.context-path=/ClientApp
2. Java 配置
在 Spring boot 2.x 中,我们可以自定义 bean WebServerFactoryCustomizer
。 我们可以使用它来更改应用程序上下文路径,端口,地址,错误页面等。
WebMvcConfig.java
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/ClientApp");
}
在 Spring boot 1.x 中,EmbeddedServletContainerCustomizer
接口用于自定义自动配置的嵌入式 Servlet 容器。
AppContainerCustomizer.java
@Component
public class AppContainerCustomizer implements EmbeddedServletContainerCustomizer {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
container.setContextPath("/ClientApp");
}
}
3. 应用参数
如果应用程序是作为超级 jar 构建的,我们也可以考虑使用此选项。
java -jar -Dserver.servlet.context-path=/ClientApp spring-boot-demo.jar
让我知道您是否知道在 spring boot 修改上下文路径中完成此更改的任何其他方法。
学习愉快!