1. 程式人生 > >Swagger2+SpringMVC 生成API介面文件

Swagger2+SpringMVC 生成API介面文件

簡單記錄一下配置的過程
- 匯入包
- 寫個配置類
- 在Controller層用註解進行註釋
- 通過一個URL就可以看到api介面文件

jar包

    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.4.0</version>
    </dependency>
    <dependency
>
<groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId
>
<version>2.8.6</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.6</version> </dependency> <dependency
>
<groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.6</version> </dependency>

配置類

@EnableWebMvc
@EnableSwagger2
@Configuration
@ComponentScan(basePackages ="com.Controller")
public class SwaggerUtil extends WebMvcConfigurationSupport {


    /**
     * Configuration 配置註解,自動在本類上下文載入一些環境變數資訊
     * EnableWebMvc
     * EnableSwagger2 使swagger2生效
     * ComponentScan("com.Controller") 需要掃描的包路徑
     *
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.Controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xxxAPI")
                .termsOfServiceUrl("www.xxxxx.com")
                .contact("藍汝琪")
                .version("1.1")
                .build();
    }
}

Controller層使用註解

常用註解
- @Api()用於類名
- @ApiOperation()用於方法名
- @ApiParam()用於引數說明
- @ApiModel()用於實體類
- @ApiModelProperty用於實體類屬性


類:
@Controller
@RequestMapping("/user")
@Api("UserController")
public class UserController {
   ......
}

方法 無引數:
 @ApiOperation(value = "祕鑰",notes = "獲取祕鑰")
    @RequestMapping(value = "/key", method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public Map getKey() {
    .....
}

方法 有引數:
 @ApiOperation(value = "登入", notes = "使用者登入")
    @ApiImplicitParam(name = "user", value = "使用者登入資料", required = true, dataType = "User")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Map login(User getUser, String key) {
    ....
}

訪問URL檢視api文件

通過專案的該url獲取文件:http://ip:prot/project_name/swagger-ui.html
例如:localhost:8080/Test/swagger_ui.html

效果圖

1.jpg