那么如何在上下文中添加 AppName 呢?
默认情况下,Spring Boot 在根上下文路径(“/”)上提供内容,但我们可以通过不同的方式对其进行更改。
1)使用application.properties/yml
For Boot 1.x, the property is server.context-path=/AppName
For Boot 2.x, the property is server.servlet.context-path=/AppName
2) 使用Java系统属性
public static void main(String[] args) {
System.setProperty("server.servlet.context-path", "/AppName");
SpringApplication.run(Application.class, args);
}
3) 使用操作系统环境变量
在 Linux 上:- $ export SERVER_SERVLET_CONTEXT_PATH=/AppName
在 Windows 上:- set SERVER_SERVLET_CONTEXT_PATH=/AppName
4) 使用命令行参数
$ java -jar app.jar --server.servlet.context-path=/AppName
5) 使用 Java 配置
使用 Spring Boot 2,我们可以使用 WebServerFactoryCustomizer:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/AppName");
}
使用 Spring Boot 1,我们可以创建 EmbeddedServletContainerCustomizer 的实例:
@Bean
public EmbeddedServletContainerCustomizer
embeddedServletContainerCustomizer() {
return container -> container.setContextPath("/AppName");
}
注意:-优先级降序排列,Spring Boot用来选择有效配置:
Java 配置
命令行参数
Java 系统属性
操作系统环境变量
当前目录中的 application.properties
类路径中的 application.properties(src/main/resources 或打包的 jar 文件)