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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容