springboot集成swagger、knife4j及常用注解的使用
1. 集成swagger2
1.1 引入依賴
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
1.2 添加Swagger配置
關(guān)鍵 RequestHandlerSelectors.basePackage(“com.gz”)
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket buildDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(buildApiInfo())
.select()
// 要掃描的API(Controller)基礎(chǔ)包
.apis(RequestHandlerSelectors.basePackage("com.gz"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo buildApiInfo() {
Contact contact = new Contact("gz","","");
return new ApiInfoBuilder()
.title("測試swagger-springbootdemo API文檔")
.description("springbootdemo后臺api")
.contact(contact)
.version("1.0.0").build();
}
}
通常情況下,swagger配置放在common模塊中,別的模塊需要集成swagger時,只需要引入common模塊就行,因此需要將SwaggerConfiguration類在META-INF/spring.facories文件里進行配置,這樣才能將SwaggerConfiguration類注冊進IOC容器。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.gzdemo.springbootdemo.config.SwaggerConfiguration
但是如果SwaggerConfiguration類在啟動類的同級目錄或子目錄下,就不需要此項配置了。
1.3 controllers和models
- TestController
@RequestMapping("/test")
@RestController
public class TestController {
@GetMapping("/hello")
public String hello(){
return "hello";
}
@PostMapping("/addUser")
public Map addUser(@RequestBody UserDto userDto){
Map<String, Object> result = new HashMap<>();
UserDto userDto1 = new UserDto();
userDto1.setName("ceshi");
userDto1.setAge(23);
userDto1.setPhone("15700000001");
userDto1.setEmail("111@qq.com");
result.put("data",userDto1);
result.put("msg","添加成功");
return result;
}
}
- UserDto
@Data
public class UserDto {
private String name;
private String phone;
private Integer age;
private String email;
}

1.4 瀏覽器訪問
瀏覽器訪問 http://localhost:8080/swagger-ui.html

2. Swagger常用注解
2.1 Swagger常用注解
在Java類中添加Swagger的注解即可生成Swagger接口文檔,常用Swagger注解如下:
- @Api:修飾整個類,描述Controller的作用
- @ApiOperation:描述一個類的一個方法,或者說一個接口
- @ApiParam:單個參數(shù)的描述信息
- @ApiModel:用對象來接收參數(shù)
- @ApiModelProperty:用對象接收參數(shù)時,描述對象的一個字段
- @ApiResponse:HTTP響應(yīng)其中1個描述
- @ApiResponses:HTTP響應(yīng)整體描述
- @ApiIgnore:使用該注解忽略這個API
- @ApiError :發(fā)生錯誤返回的信息
- @ApiImplicitParam:一個請求參數(shù)
- @ApiImplicitParams:多個請求參數(shù)的描述信息
- @ApiImplicitParam屬性:
| 屬性 | 取值 | 作用 |
|---|---|---|
| paramType | 查詢參數(shù)類型 | |
| path | 以地址的形式提交數(shù)據(jù) | |
| query | 直接跟參數(shù)完成自動映射賦值 | |
| body | 以流的形式提交 僅支持POST | |
| header | 參數(shù)在request headers 里邊提交 | |
| form | 以form表單的形式提交 僅支持POST | |
| dataType | 參數(shù)的數(shù)據(jù)類型 只作為標志說明,并沒有實際驗證 | |
| Long | ||
| String | ||
| name | 接收參數(shù)名 | |
| value | 接收參數(shù)的意義描述 | |
| required | 參數(shù)是否必填 | |
| true | 必填 | |
| false | 非必填 | |
| defaultValue | 默認值 |
2.2 測試
我們在TestController和UserDto中添加Swagger注解,代碼如下所示:
@RequestMapping("/test")
@RestController
@Api(value = "測試控制器",tags = "test")
public class TestController {
@ApiOperation("用戶測試hello")
@GetMapping("/hello")
public String hello(){
return "hello";
}
@ApiOperation("添加用戶")
@PostMapping("/addUser")
public Map addUser(@RequestBody UserDto userDto){
Map<String, Object> result = new HashMap<>();
UserDto userDto1 = new UserDto();
userDto1.setName("ceshi");
userDto1.setAge(23);
userDto1.setPhone("15700000001");
userDto1.setEmail("111@qq.com");
result.put("data",userDto1);
result.put("msg","添加成功");
return result;
}
}
@Data
public class UserDto {
@ApiModelProperty(value="姓名",required = true)
private String name;
@ApiModelProperty(value="手機號",required = true)
private String phone;
@ApiModelProperty(value="年齡",required = true)
private Integer age;
@ApiModelProperty(value="郵箱",required = true)
private String email;
}
啟動應(yīng)用,訪問 http://localhost:8080/swagger-ui.html

3. 集成knife4j
3.1 添加依賴
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
3.2 添加注解
- 在SwaggerConfiguration類上添加 @EnableKnife4j
- 在SwaggerConfiguration類上添加@Import(BeanValidatorPluginsConfiguration.class),可能會報錯,可以不用加這個,也不知道加了有什么用
3.3 瀏覽器訪問
http://localhost:8080/doc.html

4. Swagger常用注解案例
- @Api
@RestController
@Api(tags = "課表的相關(guān)接口")
@RequestMapping("/lessons")
public class LearningLessonController {
}

- @ApiOperation
@GetMapping("/now")
@ApiOperation("查詢我正在學(xué)習(xí)的課程")
public LearningLessonVO queryMyCurrentLesson() {
return lessonService.queryMyCurrentLesson();
}

- @ApiParam
@ApiOperation("查詢指定課程的學(xué)習(xí)記錄")
@GetMapping("/course/{courseId}")
public LearningLessonDTO queryLearningRecordByCourse(
@ApiParam(value = "課程id", example = "2") @PathVariable("courseId") Long courseId){
return recordService.queryLearningRecordByCourse(courseId);
}

- @ApiModel
- @ApiModelProperty
@Data
@ApiModel(description = "學(xué)習(xí)記錄")
public class LearningRecordFormDTO {
@ApiModelProperty("小節(jié)類型:1-視頻,2-考試")
@NotNull(message = "小節(jié)類型不能為空")
@EnumValid(enumeration = {1, 2}, message = "小節(jié)類型錯誤,只能是:1-視頻,2-考試")
private SectionType sectionType;
@ApiModelProperty("課表id")
@NotNull(message = "課表id不能為空")
private Long lessonId;
@ApiModelProperty("對應(yīng)節(jié)的id")
@NotNull(message = "節(jié)的id不能為空")
private Long sectionId;
@ApiModelProperty("視頻總時長,單位秒")
private Integer duration;
@ApiModelProperty("視頻的當(dāng)前觀看時長,單位秒,第一次提交填0")
private Integer moment;
@ApiModelProperty("提交時間")
private LocalDateTime commitTime;
}


總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA之IDEA連接gitlab協(xié)同開發(fā)方式
通過IDEA克隆GitLab項目實現(xiàn)代碼協(xié)同開發(fā)相較于使用SourceTree,?通過IDEA連接GitLab進行代碼協(xié)同開發(fā)更顯便捷,方法包括通過VersionControl創(chuàng)建新項目,輸入項目的git?HTTP地址和本地路徑,測試連接成功后克隆項目,修改代碼后2024-11-11
java8?Stream大數(shù)據(jù)量List分批處理切割方式
這篇文章主要介紹了java8?Stream大數(shù)據(jù)量List分批處理切割方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
使用BigDecimal進行精確運算(實現(xiàn)加減乘除運算)
這篇文章主要介紹了如何使用BigDecimal進行精確運算,最后提供了一個工具類,該工具類提供加,減,乘,除運算2013-11-11

