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("測(cè)試swagger-springbootdemo API文檔")
.description("springbootdemo后臺(tái)api")
.contact(contact)
.version("1.0.0").build();
}
}
通常情況下,swagger配置放在common模塊中,別的模塊需要集成swagger時(shí),只需要引入common模塊就行,因此需要將SwaggerConfiguration類在META-INF/spring.facories文件里進(jìn)行配置,這樣才能將SwaggerConfiguration類注冊(cè)進(jìn)IOC容器。

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.gzdemo.springbootdemo.config.SwaggerConfiguration
但是如果SwaggerConfiguration類在啟動(dòng)類的同級(jí)目錄或子目錄下,就不需要此項(xiàng)配置了。
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:修飾整個(gè)類,描述Controller的作用
- @ApiOperation:描述一個(gè)類的一個(gè)方法,或者說一個(gè)接口
- @ApiParam:?jiǎn)蝹€(gè)參數(shù)的描述信息
- @ApiModel:用對(duì)象來接收參數(shù)
- @ApiModelProperty:用對(duì)象接收參數(shù)時(shí),描述對(duì)象的一個(gè)字段
- @ApiResponse:HTTP響應(yīng)其中1個(gè)描述
- @ApiResponses:HTTP響應(yīng)整體描述
- @ApiIgnore:使用該注解忽略這個(gè)API
- @ApiError :發(fā)生錯(cuò)誤返回的信息
- @ApiImplicitParam:一個(gè)請(qǐng)求參數(shù)
- @ApiImplicitParams:多個(gè)請(qǐng)求參數(shù)的描述信息
- @ApiImplicitParam屬性:
| 屬性 | 取值 | 作用 |
|---|---|---|
| paramType | 查詢參數(shù)類型 | |
| path | 以地址的形式提交數(shù)據(jù) | |
| query | 直接跟參數(shù)完成自動(dòng)映射賦值 | |
| body | 以流的形式提交 僅支持POST | |
| header | 參數(shù)在request headers 里邊提交 | |
| form | 以form表單的形式提交 僅支持POST | |
| dataType | 參數(shù)的數(shù)據(jù)類型 只作為標(biāo)志說明,并沒有實(shí)際驗(yàn)證 | |
| Long | ||
| String | ||
| name | 接收參數(shù)名 | |
| value | 接收參數(shù)的意義描述 | |
| required | 參數(shù)是否必填 | |
| true | 必填 | |
| false | 非必填 | |
| defaultValue | 默認(rèn)值 |
2.2 測(cè)試
我們?cè)赥estController和UserDto中添加Swagger注解,代碼如下所示:
@RequestMapping("/test")
@RestController
@Api(value = "測(cè)試控制器",tags = "test")
public class TestController {
@ApiOperation("用戶測(cè)試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="手機(jī)號(hào)",required = true)
private String phone;
@ApiModelProperty(value="年齡",required = true)
private Integer age;
@ApiModelProperty(value="郵箱",required = true)
private String email;
}
啟動(dòng)應(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),可能會(huì)報(bào)錯(cuò),可以不用加這個(gè),也不知道加了有什么用
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é)類型錯(cuò)誤,只能是:1-視頻,2-考試")
private SectionType sectionType;
@ApiModelProperty("課表id")
@NotNull(message = "課表id不能為空")
private Long lessonId;
@ApiModelProperty("對(duì)應(yīng)節(jié)的id")
@NotNull(message = "節(jié)的id不能為空")
private Long sectionId;
@ApiModelProperty("視頻總時(shí)長(zhǎng),單位秒")
private Integer duration;
@ApiModelProperty("視頻的當(dāng)前觀看時(shí)長(zhǎng),單位秒,第一次提交填0")
private Integer moment;
@ApiModelProperty("提交時(shí)間")
private LocalDateTime commitTime;
}


總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java中containsKey 、 contains 方法詳解及代碼舉例詳解
在Java中,containsKey和contains方法常用于集合操作,但它們的應(yīng)用場(chǎng)景和功能有所不同,本文詳細(xì)介紹這兩種方法的用法及區(qū)別,并提供豐富的代碼實(shí)例,感興趣的朋友一起看看吧2025-09-09
SpringBoot如何監(jiān)聽redis?Key變化事件案例詳解
項(xiàng)目中需要監(jiān)聽redis的一些事件比如鍵刪除,修改,過期等,下面這篇文章主要給大家介紹了關(guān)于SpringBoot如何監(jiān)聽redis?Key變化事件的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Spring AOP的底層實(shí)現(xiàn)方式-代理模式
這篇文章主要介紹了Spring AOP的底層實(shí)現(xiàn)方式-代理模式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
關(guān)于SpringBoot整合Canal數(shù)據(jù)同步的問題
大家都知道canal是阿里巴巴旗下的一款開源工具,純java開發(fā),支持mysql數(shù)據(jù)庫,本文給大家介紹SpringBoot整合Canal數(shù)據(jù)同步的問題,需要的朋友可以參考下2022-03-03
springboot如何使用redis的incr創(chuàng)建分布式自增id
這篇文章主要介紹了springboot如何使用redis的incr創(chuàng)建分布式自增id,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
java報(bào)錯(cuò)Cause: java.sql.SQLException問題解決
本文主要介紹了java報(bào)錯(cuò)Cause: java.sql.SQLException問題解決,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
Spring Boot 如何將 Word 轉(zhuǎn)換為 PDF
這篇文章主要介紹了Spring Boot將Word轉(zhuǎn)換為 PDF,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-08-08
如何通過一個(gè)注解實(shí)現(xiàn)MyBatis字段加解密
用戶隱私很重要,因此很多公司開始做數(shù)據(jù)加減密改造,下面這篇文章主要給大家介紹了關(guān)于如何通過一個(gè)注解實(shí)現(xiàn)MyBatis字段加解密的相關(guān)資料,需要的朋友可以參考下2022-02-02

