Teo*_*ali 13 java rest swagger
我们有一个提供多个REST Web服务的Web应用程序.
在此基础上,我们通过使用注释提供资源文档.
其中一些资源将输入中的复杂对象作为主体参数.该对象的类使用@ApiModel注释
在某些情况下,我们使用Bean Validations中的@Length注释来限制某些字符串属性的长度
我们希望看到这些限制在swagger生成的文档中可见.有没有办法做到这一点 ?
PS:@Length注释的自动解释会很好但不是强制性的.任何其他方式也可以
使用@ApiModelPropertySwagger 注释,您可以使用dataType,allowableValues和range:
@ApiModelProperty(value = "Nome da lista", required = false,
dataType="java.lang.String",
allowableValues="range[-infinity, 100]")
String getNome();
Run Code Online (Sandbox Code Playgroud)
Swagger UI 上的结果:
该-infinity用于隐藏的最小值。如果您想设置最小值,只需填写数字:
allowableValues="range[5, 100]"
Run Code Online (Sandbox Code Playgroud)
小智 6
如果您使用的是Spring项目,并且使用的是Spring Fox swagger API,则可以做得很好。考虑一个豆-
public class Person {
@NotNull
private int id;
@NotBlank
@Size(min = 1, max = 20)
private String firstName;
@NotBlank
@Pattern(regexp ="[SOME REGULAR EXPRESSION]")
private String lastName;
@Min(0)
@Max(100)
private int age;
//... Constructor, getters, setters, ...
}
Run Code Online (Sandbox Code Playgroud)
使用Maven依赖-
//MAVEN
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
//MAVEN
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-bean-validators</artifactId>
<version>2.9.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
这将发挥您的魔力-@Import(BeanValidatorPluginsConfiguration.class)并且您需要在svagger配置类之上导入BeanValidatorPluginsConfiguration配置文件:
@Configuration
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
public class SpringFoxConfig {
...
}
Run Code Online (Sandbox Code Playgroud)
如果您没有用于swagger的配置类,则将其放在控制器上方
@RestController
@EnableSwagger2
@Import(BeanValidatorPluginsConfiguration.class)
@RequestMapping("/v2/persons/")
@Api(description = "Set of endpoints for Creating, Retrieving, Updating and Deleting of Persons.")
public class PersonController {
private PersonService personService;
@RequestMapping(method = RequestMethod.GET, produces = "application/json")
@ApiOperation("Returns list of all Persons in the system.")
public List getAllPersons() {
return personService.getAllPersons();
}
Run Code Online (Sandbox Code Playgroud)
使用JSR-303批注中的数据,在摇摇欲坠的文档中看起来会更好:
{
age integer ($int32)
minimum: 100
maximum: 100
firstName* string
minimumLength: 100
maxLength: 100
}
Run Code Online (Sandbox Code Playgroud)
JSR 303:Bean验证允许您注释Java类的字段以声明约束和验证规则。您可以使用以下规则来注释各个字段:-不能为null,最小值,最大值,正则表达式匹配等。这是一种已经被广泛使用的惯例。好消息是,SpringFox可以基于此类注释生成Swagger文档,因此您可以利用项目中已有的资源而无需手动编写所有约束!这非常有用,因为您的API使用者知道应提供给您的API的值有哪些限制以及期望得到哪些值。如果不包含此类注释,为我们的人员模型生成的文档看起来很简单,除了字段名称及其数据类型外,什么都没有。
是的,请参阅swagger 规范的这一部分。您可以为您的属性指定maxLength或。minLength以下是 YAML 中的示例:
definitions:
Error:
type: object
properties:
code:
type: integer
format: int32
message:
type: string
maxLength: 20
Run Code Online (Sandbox Code Playgroud)
swagger-ui 将显示如下:
| 归档时间: |
|
| 查看次数: |
7273 次 |
| 最近记录: |