【问题标题】:How to provide texts to swagger in a properties file for spring restful service?如何在 Spring RESTful 服务的属性文件中提供文本以大摇大摆?
【发布时间】:2017-06-03 21:58:01
【问题描述】:

我正在大摇大摆地创建我的 Spring Restful 服务文档。

示例请求处理程序方法及其文档如下。它有效:

@ApiOperation(value = "Returns user details", notes = "Returns a complete list of users details with a date of last modification.", response = User.class)
public Response getUser(@ApiParam(name = "userName", value = "Alphanumeric login to the application", required = true) @PathParam("userName") String userName) {
...
}

但我想将请求处理程序方法的文本提供到属性文件中的 swagger 注释中(这样做是为了不使用文档文本增加类大小)。
因此,我创建了一个名为“application-swagger.properties”的属性文件并在“application.properties”(spring.profiles.active=swagger)中启用它。 当我如下创建 api 文档时,没有显示文本。

 application-swagger.properties:
 value=Returns user details
 notes=Returns a complete list of users details with a date of last modification.

控制器类:

@Controller
@Profile("swagger")
public class UserController{
    .
    .
    @ApiOperation(value = "${value}", notes = ${notes}", response = User.class)
    public Response getUser(@ApiParam(name = "userName", value = "Alphanumeric login to the application", required = true) @PathParam("userName") String userName) {
    ...
    }
    .
    .
}

有没有办法从属性文件中将文本放入 swagger 注释?感谢您的帮助。

【问题讨论】:

  • Swagger 注释不允许使用变量设置“值、注释、昵称”键。所以我使用静态类和静态最终变量而不是属性文件解决了这个问题。例如,在请求处理程序方法中,“reqMethod1”值设置为:@ApiOperation(value = "SwaggerProps.REQMETHOD1_Value")
  • 更多信息:这不仅是大摇大摆的注释,而是一般的所有注释。
  • @ApiResponses(value = { @ApiResponse(code = 200, message = "已成功填充员工详细信息",response = Employee.class), - 是否有任何选项可以传递代码,来自应用程序的消息值.properties 而不是硬编码?我使用的是 springfox 2.9.x 和 Spring 4.3.15 - REST API

标签: java spring rest swagger


【解决方案1】:

回答这个问题已经很晚了,但如果有人需要帮助,可以参考它。

步骤:

  1. 创建一个属性文件,例如swagger.properties
  2. 将所需消息作为键值对输入,其中键将用作占位符 - 例如person.id=此人的唯一标识符
  3. 插入占位符而不是注释文本 - 例如${person.id}
  4. 在类级别的配置中注册属性文件 - 例如。 @PropertySource("classpath:swagger.properties")

使用 Spring Boot 1.5 和 Swagger 2.8,不确定以前的版本。

参考取自详细article 大致相同。

【讨论】:

  • 感谢您的回答,它就像您提到的那样有效,但不幸的是,不适用于“示例”属性。在那里你必须复制粘贴值。
  • 这项工作适用于 ApiOperation 注释中的属性“值”。也适用于 RequestMapping 注释中的属性“名称”和“值”。但遗憾的是,对于 ApiResponse 注释中的属性“消息”不起作用
  • 有什么方法可以使用 Spring 4 将运行时值传递给 @ApiResponse(code = , message= )
【解决方案2】:

您不能这样做,因为注释值需要一个常量,但在您的场景中它不是一个常量。 请参考accected values in the annotaion java 文档,说它必须是一个常量。

在您的情况下,最简单/可读的方法是将所有常量移动到单独的类而不是属性文件中。

【讨论】:

    猜你喜欢
    • 2020-03-18
    • 2015-12-14
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多