码迷,mamicode.com
首页 > 其他好文 > 详细

Swagger2在项目中的使用

时间:2018-09-12 19:59:45      阅读:386      评论:0      收藏:0      [点我收藏+]

标签:integer   设置   lse   server   selectors   restapi   docke   ref   use   

小伙伴大家好,今天小编为大家介绍一个简单的测试工具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:

技术分享图片

 

 这样便可完成测试。

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

 

Swagger2在项目中的使用

标签:integer   设置   lse   server   selectors   restapi   docke   ref   use   

原文地址:https://www.cnblogs.com/snowstorm/p/9636286.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!