1、创建一个springboot项目
2、添加swagger2的maven依赖
<!-- swagger生成接口API -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<!-- 接口API生成html文档 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
3.配置Swagger2
现在Swagger2还不能为我们生成API文档,因为我们还没有对它进行配置.
我们需要创建一个配置类,进行如下配置:
/** * @Author hebo * @Date 17:07 2019/3/5 */ @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .forCodeGeneration(false) .select() .apis(RequestHandlerSelectors.basePackage("com.nwpusct.csal.controller"))//所有接口包 .paths(PathSelectors.any()) .build(); }
private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("智能数字射线检测 API")//标题 .description("description:项目摘要")//描述 .termsOfServiceUrl(" ")//(不可见)条款地址,公司内部使用的话不需要配 .contact(new Contact("bobo","https://swagger.io/","15291937382@163.com")) .version("1.0")//版本号 .build(); }}
通过@configuration注解,让spring来加载此类的配置。basePackage内的包名也就是,接口存在的包,swagger会扫描并显示其下的接口
*注意,应该在springboot的Application类下添加@EnableSwagger2注解来启用swagger2
4、接下来就可以通过使用注解,在接口类中添加文档内容
@Api 用于controller类上 对类的功能进行描述
@ApiOperation 用在controller方法上 对类的方法进行描述
@ApiImplicitParam 用在Controller方法上 对方法需要传进来的参数进行描述
paramType 有path以地址形式提交数据、query直接跟参数完成自动映射赋值(get方法使用)、body以流的形式提交仅支持POST(@requestBody)、header参数在request headers里面提交、form以form表单形式提交仅支持POST,dataType如果是自定义的实体对象,需要在请求参数时加上@requestBody注解
@ApiImplicitParams 用在controller方法上,如果一个方法有多个请求参数,需要有该注解将@ApiImplicitParam包在里面
@ApiResponse 用在controller方法上,定义返回的错误号,以及其表达的含义
@ApiResponses 用在controller方法上, 当需要定义多个@ApiResponse时,需要用到该注解将它们包在里面
@ApiModel 用在返回对象类上 描述返回对象的意义
@ApiModelProperty 用在实体对象的字段上 用于描述字段含义
5.进入swagger界面:http://localhost:9080/swagger-ui.html#/