方法不止一种,具体取决于你是否使用 spring-boot:
- 在 application.properties/yml 文件中:
server.servlet.context-path=/newName
- Java 系统属性:
您还可以在初始化上下文之前将上下文路径设置为 Java 系统属性:
public static void main(String[] args)
{
System.setProperty("server.servlet.context-path", "/newName");
SpringApplication.run(Application.class, args);
}
- 操作系统环境变量:
Linux:
导出 SERVER_SERVLET_CONTEXT_PATH=/newName
窗户:
设置 SERVER_SERVLET_CONTEXT_PATH=/newName
上面的环境变量是针对Spring Boot 2.x.x的,如果我们有1.x.x,变量就是SERVER_CONTEXT_PATH。
- 命令行参数
我们也可以通过命令行参数动态设置属性:
java -jar app.jar --server.servlet.context-path=/newName
- 使用 Java 配置
在 Spring Boot 2 中,我们可以使用 WebServerFactoryCustomizer:
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
return factory -> factory.setContextPath("/newName");
}
使用 Spring Boot 1,我们可以创建 EmbeddedServletContainerCustomizer 的实例:
@Bean
public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {
return container -> container.setContextPath("/newName");
}
-
Eclipse + Maven
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<wtpversion>2.0</wtpversion>
<wtpContextName>newName</wtpContextName>
</configuration>
</plugin>
- Eclipse + Gradle
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
eclipse {
wtp {
component {
contextPath = 'newName'
}
}
}
以下链接可能会有所帮助: