Swagger2+SpringMVC 生成API接口文档

简单记录一下配置的过程

  • 导入包
  • 写个配置类
  • 在Controller层用注解进行注释
  • 通过一个URL就可以看到api接口文档

jar包

    
      io.springfox
      springfox-swagger2
      2.4.0
    
    
      io.springfox
      springfox-swagger-ui
      2.4.0
    
    
    
      com.fasterxml.jackson.core
      jackson-core
      2.8.6
    
    
    
      com.fasterxml.jackson.core
      jackson-databind
      2.8.6
    
   
    
      com.fasterxml.jackson.core
      jackson-annotations
      2.8.6
    

配置类

@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

效果图

Swagger2+SpringMVC 生成API接口文档_第1张图片
1.jpg

你可能感兴趣的:(Swagger2+SpringMVC 生成API接口文档)