Swagger2 -- API文檔

官網(wǎng):https://swagger.io/

Swagger2應用組成

1、配置Maven依賴

<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>

2、Swagger配置類

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        // springfox.documentation.service.Contact
        Contact contact = new Contact("團隊名", "www.my.com", "my@my.com");
        return new ApiInfoBuilder()
                .title("文檔標題")
                .description("文檔描述")
                .contact(contact)   // 聯(lián)系方式
                .version("1.1.0")  // 版本
                .build();
    }
}

3、Spring MVC配置

<bean class="com.hogen.config.SwaggerConfig"></bean>
<mvc:default-servlet-handler/>
<!-- 根據(jù)profile配置不同的location,就可以在生產(chǎn)環(huán)境中禁用Swagger -->
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/"/> 
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/"/>

4、在Controller中使用Swagger注解

@RestController
@Api(tags="接口所在的類")
@RequestMapping ("/my")
public class MyController {

    @RequestMapping(value="/list", method=RequestMethod.POST)
    @ApiOperation(value = "接口名", notes = "接口描述", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "length",value = "參數(shù)1", required = true, paramType = "path"),
            @ApiImplicitParam(name = "size",value = "參數(shù)2", required = true, paramType = "query"),
            @ApiImplicitParam(name = "page",value = "參數(shù)3", required = true, paramType = "header"),
            @ApiImplicitParam(name = "total",value = "參數(shù)4", required = true, paramType = "form"),
            @ApiImplicitParam(name = "start",value = "參數(shù)5",dataType = "string", paramType = "body")
    })
    public String register(){
        return "has permission";
    }
}

5、訪問接口文檔:localhost:8080/swagger-ui.html
6、swagger-ui.html 中導出的API文件可以在 Swagger Editor(http://editor.swagger.io/) 中打開
7、在Swagger Editor中,Generate Client 可以生成html版的API文檔

整合 Spring Security

                 // 配置權限豁免,才能正常訪問 localhost:8080/swagger-ui.html
                .antMatchers("/swagger-ui.html").permitAll()
                .antMatchers("/swagger-resources/**").permitAll()
                .antMatchers("/webjars/**").permitAll()
                .antMatchers("/v2/api-docs").permitAll()
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容