小伙伴大家好,今天小编为大家介绍一个简单的测试工具swagger2。大家以前进行测试都是在浏览器里面或者一些工具(postman等)进行测试,这样稍微有点麻烦。大家了解下swagger.

1.在pom里面添加jar依赖,这里面选的swagger2是版本2.8.0

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

2.添加配置文件SwaggerConfig

@EnableSwagger2
@Configuration
public class SwaggerConfig {

//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
@Value(value = "${swagger.enabled}")
Boolean swaggerEnabled;

@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.study.springcloud"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("SpringBoot-Swagger2集成和使用-demo示例")
.description("springboot | swagger")
// 作者信息
.contact(new Contact("snows", "https://home.cnblogs.com/u/snowstorm/", "1083270492@qq.com"))
.version("1.0.0")
.build();
}
}

3.添加相关注解

3.1在请求对象上加注解,如ApiModelProperty
public class Student implements Serializable {

@Id
@GeneratedValue
private Integer id;
@Column(length = 50)
@ApiModelProperty(value="姓名",dataType="String",name="name",example="snows")
private String name;
@Column(length = 50)
@ApiModelProperty(value="班级",dataType="String",name="grade",example="研二")
private String grade;
}
3.2在请求方法上加注解
@ApiOperation(value="学生新增")
@PostMapping("/save")
public Boolean delete(@RequestBody Student student){
try {
studentService.save(student);
return Boolean.TRUE;
}catch (Exception e){
return Boolean.FALSE;
}
}

4.启动并访问

 

application.yml文件如下

server:
port: 1001
context-path: /
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/db_springcloud
username: root
password: snows
jpa:
hibernate:
ddl-auto: update
show-sql: true
swagger:
enabled: true

访问路径:http://localhost:1001/swagger-ui.html,页面如下:

 


 

5.点开学生API

找到/stu/save学生新增点击右上角try it out,然后输入需要参数后点击execute:

 

 这样便可完成测试。

希望能够帮到小伙伴们,谢谢。