代码之家  ›  专栏  ›  技术社区  ›  Dreamer

Spring启动应用程序启动时没有正确的应用程序名称

  •  2
  • Dreamer  · 技术社区  · 7 年前

    ./mvnw spring-boot:run
    

    当前的spring启动应用程序可以用当前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
    

    但仍然没有解决问题。

    4 回复  |  直到 7 年前
        1
  •  8
  •   Nishant Bhardwaz    7 年前

    那么如何在上下文中添加AppName呢?

    默认情况下,springboot服务于根上下文路径(/)上的内容,但是我们可以用不同的方式来更改它。
    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) 使用OS环境变量
    $ export SERVER_SERVLET_CONTEXT_PATH=/AppName
    在W上indows:- set SERVER_SERVLET_CONTEXT_PATH=/AppName

    $ java -jar app.jar --server.servlet.context-path=/AppName
    

    5) 使用Java配置

    有了弹簧靴2,我们可以 WebServerFactoryCustomizer :

    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>
      webServerFactoryCustomizer() {
        return factory -> factory.setContextPath("/AppName");
    }
    

    使用springboot1,我们可以创建 EmbeddedServletContainerCustomizer :

    @Bean
    public EmbeddedServletContainerCustomizer
      embeddedServletContainerCustomizer() {
        return container -> container.setContextPath("/AppName");
    }
    

    Note:-

    Java配置
    命令行参数


    当前目录中的application.properties

        2
  •  0
  •   Behe    7 年前

    • 弹簧靴1.x: server.contextPath=/AppName
    • 弹簧靴2.x: server.servlet.contextPath=/AppName
        3
  •  0
  •   Passarinho    7 年前

    server.servlet.context-path 用于弹簧防尘套2.x server.context-path 对于弹簧1.x 在application.properties文件中。

        4
  •  0
  •   Tạ Anh Tú    7 年前

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