swagger简单应用
简单介绍好处就是借助Swagger可以为用户,团队和企业简化API开发。
是一款RESTFUL接口的文档在线自动生成+功能测试功能软件
- 集成简单,学习成本低
- 能有效简化团队协作成本
1. 使用springboot集成swagger引入如下依赖:
<!-- https://mvnrepository.com/artifact/com.spring4all/swagger-spring-boot-starter -->
<dependency>
<groupId>com.spring4all</groupId>
<artifactId>swagger-spring-boot-starter</artifactId>
<version>1.9.0.RELEASE</version>
</dependency>
2. application.yml配置
swagger:
enabled: true #是否开启swagger 默认true
base-package: com.itmck.web
contact:
name: miaochangke
email: 8080@163.com
url:
title: swagger测试项目标题
description: 文档描述
ui-config:
json-editor: true #启用json编辑器
spring:
servlet:
multipart: ##自定上传文件大小
max-file-size: 10MB
max-request-size: 10MB
3.启动类上启用swagger注解 @EnableSwagger2Doc 如下:
@EnableSwagger2Doc
@SpringBootApplication
public class MybatisPlusDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisPlusDemoApplication.class, args);
}
}
4.swagger注解详解:
@Api:用在请求的类上,表示对类的说明
tags="说明该类的作用,可以在UI界面上看到的注解"
value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
@ApiIgnore: 类上,表示隐藏这个类不在swagger-ui中展示
@ApiOperation:用在请求的方法上,说明方法的用途、作用
value="说明方法的用途、作用"
notes="方法的备注说明"
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
name:参数名
value:参数的汉字说明、解释
required:参数是否必须传
paramType:参数放在哪个地方
· header --> 请求参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body-->请求参数的获取:@RequestBody(代码中接收注解)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="int" 代表请求参数类型为int类型,当然也可以是Map、User、String等;
defaultValue:参数的默认值
@ApiResponses:用在请求的方法上,表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
code:数字,例如400
message:信息,例如"请求参数没填好"
response:抛出异常的类
@ApiModel:用于响应类上,表示一个返回响应数据的信息
(这种一般用在post创建的时候,使用@RequestBody这样的场景,
请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:用在属性上,描述响应类的属性
5:swaggwer注解演示:
控制器演示 这里基本使用比较多注意事项演示如下:
@Slf4j
@Api(value = "SwaggerActionController文档测试",tags = "控制器作用")
@RestController
public class SwaggerActionController {
@ApiOperation(value = "swaggwer测试", notes = "swagger使用演示1")
@PostMapping("/hello")
public Student helloSwagger(@RequestBody Student student) {
return student;
}
@ApiOperation(value = "swaggwer测试2", notes = "swagger使用演示2")
@GetMapping("hello2")
public Student helloSwagger2(Student student) {
return student;
}
@ApiOperation(value = "swaggwer测试3", notes = "swagger使用演示3")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名", dataType = "String",paramType = "path"),
@ApiImplicitParam(name = "age", value = "年龄", dataType = "Integer",paramType = "path")
})
@GetMapping("hello3/{name}/{age}")
public String helloSwagger3(@PathVariable String name,@PathVariable int age) {
return "my name is:"+name+" and age is : "+age;
}
@ApiOperation(value = "swaggwer测试4", notes = "swagger使用演示4")
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名", dataType = "String",paramType = "path"),
@ApiImplicitParam(name = "address", value = "地址", dataType = "String",paramType = "query")
})
@GetMapping("hello4/{name}")
public String helloSwagger4(@PathVariable String name,@RequestParam String address) {
return "my name is:"+name+" address: "+address;
}
@ApiOperation(value = "上传swagger演示", notes = "swagger演示上传",consumes = "multipart/form-data",hidden = true)
@PostMapping("hello5/{name}")
public String helloSwagger5(@PathVariable String name,@RequestParam("qqfile") MultipartFile file) {
String name1 = file.getName();
return "my name is:"+name+"正在测试上传文件:"+name1;
}
@ApiOperation(value = "swaggwer隐藏方法", notes = "swaggwer隐藏方法",hidden = true)
@PostMapping("hello6/{name}")
public String helloSwagger6(@PathVariable String name) {
return "my name is:"+name;
}
Model演示
@Data
@ApiModel(value = "Student类")
public class Student {
@ApiModelProperty(value = "姓名",name = "name",example = "itmck",dataType ="String")
private String name;
@ApiModelProperty(value = "年龄",name = "age",example = "25")
private int age;
@ApiModelProperty(value = "邮箱",name = "email",example = "17355805355@163.com")
private String email;
@ApiModelProperty(value = "地址",name = "address",example = "安徽阜阳")
private String address;
//hidden = true:隐藏这个方法
@ApiModelProperty(value = "性别",name = "sex",example = "男",hidden = true)
private String sex;
}
6:本地启动后访问:http://127.0.0.1:8080/swagger-ui.html 界面如下:
swaggwe2集成方式2
1引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
5配置swagger信息
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.itmk"))// API接口包扫描路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,https://mp.csdn.net/console/article")
.termsOfServiceUrl("https://mp.csdn.net/console/article")
.version("1.0")
.build();
}
}
启动类 @EnableSwagger2
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwagger2Application.class, args);
}
}
鉴权swagger-ui.html
1.引入如下依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.application.yml新增
spring:
security:
user:
name: mck
password: 123
3.这时候访问http://127.0.0.1:8080/swagger-ui.html会出现如下:
4.自定义鉴权规则:如只想拦截 /swagger-ui.html 其余不拦截.增加如下代码
@EnableWebSecurity
@Configuration
public class SwaggerConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()//禁用csrf跨站请求伪造
.authorizeRequests()//认证请求
.antMatchers("/swagger-ui.html").authenticated() //这里只认证 /swagger-ui.html
.anyRequest().permitAll()//其他放行
.and().formLogin()
.and().headers().frameOptions().disable();
}
}
题外话.如何优雅的进行入参的非空验证,避免出现过多垃圾代码
if(StringUtils.isBlank(student.getName())){
return "姓名非空";
}
controller层可以使用 @Validated与 BindingResult
public Map<String,Object> helloSwagger0(@Validated @RequestBody Student student, BindingResult bindingResult) {
Map<String,Object> map = new HashMap<>();
if (bindingResult.hasErrors()){
bindingResult.getFieldErrors().forEach(error->{
log.error("参数:{},校验失败,原因:{}",error.getField(),error.getDefaultMessage());
});
map.put("message", "非空校验失败");
map.put("flag", false);
}
return map;
}
Model
@Data
public class Student {
@NotNull(message = "姓名不能为空")
private String name;
}
更多关于验证@Validated 使用自行百度细节