springBoot系列(4)--集成swagger-ui

springboot的swagger2依賴引入

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

添加swaggerconfig的配置類

當然這裏可以直接在配置文件裏面添加配置.我這裏直接添加 了一個配置類,首先通過@EnableSwagger2註解啓動swagger2,然後配置一個Docket bean,配置映射路徑和要掃描的接口的位置,在apiInfo中,主要配置一下Swagger2文檔網站的信息,例如網站的title,網站的描述,聯繫人的信息,使用的協議等等。

/**
 * @Classname SwaggerConfig
 * @Description swagger
 * @Date 2020/5/22 8:47
 * @Created by corey
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.nvn.controller"))
                .paths(PathSelectors.any())
                .build().apiInfo(new ApiInfoBuilder()
                        .title("SpringBoot整合Swagger")
                        .description("SpringBoot整合Swagger,詳細信息......")
                        .version("9.0")
                        .contact(new Contact("corey", "https://blog.csdn.net/CoreyXuu", "[email protected]"))
                        .license("The Apache License")
                        .licenseUrl("https://blog.csdn.net/CoreyXuu")
                        .build());
    }

}

配置完成後啓動項目

地址欄輸入:http://localhost:8080/swagger-ui.html
在這裏插入圖片描述
項目啓動很順利

swagger項目接口管理配置

這裏簡單說明下swagger的註解

  1. @Api註解可以用來標記當前Controller的功能。
  2. @ApiOperation註解用來標記一個方法的作用。
  3. @ApiImplicitParam註解用來描述一個參數,可以配置參數的中文含義,也可以給參數設置默認值,這樣在接口測試的時候可以避免手動輸入。
  4. 如果有多個參數,則需要使用多個@ApiImplicitParam註解來描述,多個@ApiImplicitParam註解需要放在一個@ApiImplicitParams註解中。
  5. 需要注意的是,@ApiImplicitParam註解中雖然可以指定參數是必填的,但是卻不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架內必填,拋棄了Swagger2,這個限制就沒用了,所以假如開發者需要指定一個參數必填,@RequestParam(required = true)註解還是不能省略。
  6. 如果參數是一個對象@ApiModel
    加上註解後啓動項目
    在這裏插入圖片描述
    返回參數:
    在這裏插入圖片描述
    代碼上傳到 https://github.com/coreyxuy/springboot-email.git
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章