Swagger2在項目中的使用


小伙伴大家好,今天小編為大家介紹一個簡單的測試工具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:

 

 這樣便可完成測試。

希望能夠幫到小伙伴們,謝謝。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM