SpringBoot Swagger2 可視化API

在參考了大部分博客中,發(fā)現(xiàn)關(guān)于Swagger-ui的文檔很多,但是要迅速的完成一個Demo還是需要調(diào)試,查找文檔,所有記錄下了這篇文章.

  1. 導(dǎo)入依賴
<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.2.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.2.2</version>
</dependency>

2.配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                        .apiInfo(apiInfo())
                        .select()
                                                      
                        .apis(RequestHandlerSelectors.basePackage("com.tanoak.controller"))//需要掃描的包
                        .paths(PathSelectors.any())
                        .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                        .title("Spring Boot中使用Swagger2構(gòu)建RESTful APIs")
                        .description("更多Spring Boot相關(guān)文章:http://www.itdecent.cn/u/39192052658a")
                        .termsOfServiceUrl("http://www.itdecent.cn/u/39192052658a")
                        .contact("tanoak")
                        .version("1.0")
                        .build();
    }
}

3.書寫Controller

    @GetMapping("json")
    @ApiOperation(value="Map<String,String>", notes="返回MapJson對象")
    @ApiImplicitParam(name = "map", value = "Map形式Json對象", required = true, dataType = "Map")
    public Map<String ,String> toJson(){
        Map<String ,String> map = new HashMap<>() ;
        map.put("name","Jack");
        map.put("site","江西南昌");
        return map ;
    }

常用注解詳細說明 ps:這里只有部分,更多請參考官方文檔

對象屬性    @ApiModelProperty   用在出入?yún)?shù)對象的字段上
協(xié)議集描述   @Api    用于controller類上
協(xié)議描述    @ApiOperation   用在controller的方法上
Response集   @ApiResponses   用在controller的方法上
Response    @ApiResponse    用在 @ApiResponses里邊
非對象參數(shù)集  @ApiImplicitParams  用在controller的方法上
非對象參數(shù)描述 @ApiImplicitParam   用在@ApiImplicitParams的方法里邊
描述返回對象的意義   @ApiModel   用在返回對象類上

訪問http://localhost:2001/swagger-ui.html ps:2001是我的端口號,自行更改
到這里就結(jié)束了,來張圖片,看看效果

運行效果

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容