PCa*_*che 2 swagger spring-boot springfox
我正在尝试按照 Springfox Swagger 的文档来让 Java Bean 验证工作( http://springfox.github.io/springfox/docs/current/#springfox-support-for-jsr-303),但它们是没有出现在 Swagger UI 中。
这是我的弹簧配置:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@EnableSwagger2
@Import({springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration.class})
@Configuration
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("My API")
.build();
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的请求映射:
@ApiOperation(value = "Use to get token for internal applications")
@PostMapping(value = AuthUris.TOKEN)
public AuthResponse token(@Valid @RequestBody AuthRequest authRequest) {
// implementation omitted
}
Run Code Online (Sandbox Code Playgroud)
这是我的 POJO:
@ApiModel
public class AuthRequest {
@ApiModelProperty
@NotNull
@Size(min = 4, max = 50)
private String username;
@NotNull
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在 Swagger UI 中捕获 NotNull 和 Size 注释,但事实并非如此。请帮助我了解这应该如何工作。谢谢你。
所以感谢/sf/users/560866561/我确实看到他们在工作。但是,我必须将鼠标悬停在该字段上才能像@Size 一样思考。请参阅下面的屏幕截图。
如果您使用的是springfox版本2.7.0,则@NotNull和@Size注释都应该有效。
您的@NotNull注释已经在password field.
如果@ApiModelProperty某个字段存在注释,则它优先于@NotNull注释。username场上就是这种情况。它显示为optional因为注释的required属性默认@ApiModelProperty设置为false。
如果你使用springfox版本2.7.0并且不使用@ApiModelProperty注解,模型将显示为:
例如,如果您输入的用户名小于最小大小 4,您将收到以下异常:
{
"timestamp": 1511550365198,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MethodArgumentNotValidException",
"errors": [
{
"codes": [
"Size.authRequest.username",
"Size.username",
"Size.java.lang.String",
"Size"
],
"arguments": [
{
"codes": [
"authRequest.username",
"username"
],
"arguments": null,
"defaultMessage": "username",
"code": "username"
},
50,
4
],
"defaultMessage": "size must be between 4 and 50",
"objectName": "authRequest",
"field": "username",
"rejectedValue": "s",
"bindingFailure": false,
"code": "Size"
}
],
"message": "Validation failed for object='authRequest'. Error count: 1",
"path": "/tokens"
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7452 次 |
| 最近记录: |