1、依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2、swagger2配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2Configuration {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.XXX"))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("XXXXX服务") //设置文档的标题
.description("该服务XXXXXXX") // 设置文档的描述
.version("1.0.0") // 设置文档的版本信息-> 1.0.0 Version information
.termsOfServiceUrl("") // 设置文档的License信息->1.3 License information
.build();
}
}
3、swagger2的访问地址
http://localhost:8080/swagger-ui.html
4、常用注解
(1)@Api :用于类
表示这个类是swagger资源
tags-表示说明(若含多个值,会生成多个list)
value-也是说明,可以使用tags替代
(2)@ApiOperation :用于方法
表示一个http请求
value-用于方法描述
notes-用于提示内容
tags-可以重新分组(视情况而用)
(3)@ApiParam :用于参数
表示对参数的添加元数据(说明或是否必填等)
name-参数名
value-参数说明
required-是否必填
(4)@ApiModel :用于实体类
表示对类进行说明,用于参数用实体类接收
value-表示对象名
decription-描述
(5)@ApiModelProperty :用于实体类中的方法、字段
表示对model属性的说明或者数据操作更改
value-字段说明
name-重写属性名字
dataType-重写属性类型
required-是否必填
example-举例说明
hidden-隐藏
(6)@ApiIgnore :用于类、方法、参数
表示这个方法或类被忽略
(7)@ApiImplicitParam :用于方法
表示单独的请求参数
(8)@ApiImplicitParams :用于方法
表示包含多个@ApiImplicitParam
name-参数名
value-参数说明
dataType-数据类型
paramType-参数类型
example-举例说明
5、在Security中的配置
SpringBoot项目中如果集成了Spring Security,在不做额外配置的情况下,Swagger2文档会被拦截。解决方法是在Security的配置类中重写configure方法添加白名单即可:
@Override
public void configure ( WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/swagger-ui.html")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}