【问题标题】:Spring boot application start without proper application nameSpring Boot 应用程序启动时没有正确的应用程序名称
【发布时间】:2019-03-28 05:54:12
【问题描述】:

运行时

./mvnw spring-boot:run

当前的 Spring Boot 应用程序可以在当前 URL 的浏览器中打开

http://localhost:8080/

但不是

http://localhost:8080/AppName

所以即使在 Swagger 中,API 也必须像这样检索

http://localhost:8080/api/swagger.json

而不是这个

http://localhost:8080/AppName/api/swagger.json

那么如何在上下文中添加AppName?在 web.xml 是基于 xml 的过去很容易,在基于 java 的配置中我已经添加了

spring.application.name=AppName

但仍然没有解决问题。

【问题讨论】:

标签: java spring spring-boot


【解决方案1】:

那么如何在上下文中添加 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 文件)

【讨论】:

  • 我已经使用了 1 和 2 选项,但仍然没有工作。
【解决方案2】:

设置上下文路径

  • Spring Boot 1.x:server.contextPath=/AppName
  • Spring Boot 2.x:server.servlet.contextPath=/AppName

【讨论】:

    【解决方案3】:

    你应该使用 server.servlet.context-path 用于 Spring Boot 2.x server.context-path 用于 Spring 1.x 在您的 application.properties 文件中。

    【讨论】:

      【解决方案4】:

      在您的 application.properties 中添加以下行(适用于 Spring Boot 1.x): server.contextPath=/AppName 如果您的版本是 2.x,请使用以下内容: server.servlet.contextPath=/AppName

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-17
        • 2020-02-09
        • 1970-01-01
        • 1970-01-01
        • 2015-05-10
        • 2020-08-04
        • 2017-05-12
        相关资源
        最近更新 更多