Swagger
1. Add dependencies
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
复制代码
2. Write a configuration class
2.1, a single group
@Configuration
@EnableSwagger2
@Profile({"dev", "test"}) // 只在dev和test环境生效
public class SwaggerConfiguration {
@Bean
public Docket defaultApi1() {
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiIanfo()).
groupName("1.0版本").
select().
apis(RequestHandlerSelectors.basePackage("com.zhf.stujpa.controller")).
paths(PathSelectors.any()).
build();
}
public ApiInfo apiIanfo(){
return new ApiInfoBuilder().
title("我的测试接口").
description("我的测试接口").
contact(new Contact("张海峰","http://XX.com","[email protected]")).
build();
}
}
复制代码
2.2, multiple groups
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket defaultApi1() {
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiIanfo()).
groupName("用户控制器").
select().
apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.user")).
/**
通过路径来分组
PathSelectors.ant("/api/station/operation/**")
*/
paths(PathSelectors.any()).
build();
}
public ApiInfo apiIanfo(){
return new ApiInfoBuilder().
title("我的测试接口").
description("我的测试接口").
contact(new Contact("张海峰","http://XX.com","[email protected]")).
build();
}
@Bean
public Docket defaultApi1() {
return new Docket(DocumentationType.SWAGGER_2).
apiInfo(apiIanfo()).
groupName("角色控制器").
select().
apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller.role")).
paths(PathSelectors.any()).
build();
}
}
复制代码
Knife4j
1. Add dependencies
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.7</version>
</dependency>
复制代码
2. Write a configuration class
2.1, a single group
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfiguration {
@Bean(value = "defaultApi1")
public Docket defaultApi1() {
Docket docket=new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//分组名称
.groupName("2.X版本")
.select()
//这里指定Controller扫描包路径
.apis(RequestHandlerSelectors.basePackage("com.zhf.stu.controller"))
.paths(PathSelectors.any())
.build();
return docket;
}
public ApiInfo apiIanfo(){
return new ApiInfoBuilder().
title("我的测试接口").
description("我的测试接口").
contact(new Contact("张海峰","http://XX.com","[email protected]")).
build();
}
}
复制代码
2.2, multiple groups
- Create a configuration property class/
@Data
@ConfigurationProperties(prefix = "stu.swagger")
public class SwaggerProperties {
private String title = "在线文档"; //标题
private String group = ""; //自定义组名
private String description = "在线文档"; //描述
private String version = "1.0"; //版本
private Contact contact = new Contact(); //联系人
private String basePackage = "com.zhf.stu"; //swagger会解析的包路径
private List<String> basePath = new ArrayList<>(); //swagger会解析的url规则
private List<String> excludePath = new ArrayList<>();//在basePath基础上需要排除的url规则
private Map<String, DocketInfo> docket = new LinkedHashMap<>(); //分组文档
public String getGroup() {
if (group == null || "".equals(group)) {
return title;
}
return group;
}
@Data
public static class DocketInfo {
private String title = "在线文档"; //标题
private String group = ""; //自定义组名
private String description = "在线文档"; //描述
private String version = "1.0"; //版本
private Contact contact = new Contact(); //联系人
private String basePackage = ""; //swagger会解析的包路径
private List<String> basePath = new ArrayList<>(); //swagger会解析的url规则
private List<String> excludePath = new ArrayList<>();//在basePath基础上需要排除的url
public String getGroup() {
if (group == null || "".equals(group)) {
return title;
}
return group;
}
}
@Data
public static class Contact {
private String name = "pinda"; //联系人
private String url = ""; //联系人url
private String email = ""; //联系人email
}
}
复制代码
- Create application.yml file
server:
port: 10086
stu:
swagger:
enabled: true #是否启用swagger
docket:
user:
title: 用户模块
base-package: com.zhf.stu.controller.user
menu:
title: 角色模块
base-package: com.zhf.stu.controller.role
复制代码
- Create configuration class SwaggerAutoConfiguration
@Configuration
@ConditionalOnProperty(name = "pinda.swagger.enabled", havingValue = "true",
matchIfMissing = true)
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerAutoConfiguration implements BeanFactoryAware {
@Autowired
SwaggerProperties swaggerProperties;
private BeanFactory beanFactory;
@Bean
@ConditionalOnMissingBean
public List<Docket> createRestApi(){
ConfigurableBeanFactory configurableBeanFactory =
(ConfigurableBeanFactory) beanFactory;
List<Docket> docketList = new LinkedList<>();
// 没有分组
if (swaggerProperties.getDocket().isEmpty()) {
Docket docket = createDocket(swaggerProperties);
configurableBeanFactory.registerSingleton(swaggerProperties.getTitle(),
docket);
docketList.add(docket);
return docketList;
}
// 分组创建
for (String groupName : swaggerProperties.getDocket().keySet()){
SwaggerProperties.DocketInfo docketInfo =
swaggerProperties.getDocket().get(groupName);
ApiInfo apiInfo = new ApiInfoBuilder()
//页面标题
.title(docketInfo.getTitle())
//创建人
.contact(new Contact(docketInfo.getContact().getName(),
docketInfo.getContact().getUrl(),
docketInfo.getContact().getEmail()))
//版本号
.version(docketInfo.getVersion())
//描述
.description(docketInfo.getDescription())
.build();
// base-path处理
// 当没有配置任何path的时候,解析/**
if (docketInfo.getBasePath().isEmpty()) {
docketInfo.getBasePath().add("/**");
}
List<Predicate<String>> basePath = new ArrayList<>();
for (String path : docketInfo.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> excludePath = new ArrayList<>();
for (String path : docketInfo.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.groupName(docketInfo.getGroup())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.basePackage(docketInfo.getBasePackage()))
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
.build();
configurableBeanFactory.registerSingleton(groupName, docket);
docketList.add(docket);
}
return docketList;
}
//构建 api文档的详细信息
private ApiInfo apiInfo(SwaggerProperties swaggerProperties) {
return new ApiInfoBuilder()
//页面标题
.title(swaggerProperties.getTitle())
//创建人
.contact(new Contact(swaggerProperties.getContact().getName(),
swaggerProperties.getContact().getUrl(),
swaggerProperties.getContact().getEmail()))
//版本号
.version(swaggerProperties.getVersion())
//描述
.description(swaggerProperties.getDescription())
.build();
}
//创建接口文档对象
private Docket createDocket(SwaggerProperties swaggerProperties) {
//API 基础信息
ApiInfo apiInfo = apiInfo(swaggerProperties);
// base-path处理
// 当没有配置任何path的时候,解析/**
if (swaggerProperties.getBasePath().isEmpty()) {
swaggerProperties.getBasePath().add("/**");
}
List<Predicate<String>> basePath = new ArrayList<>();
for (String path : swaggerProperties.getBasePath()) {
basePath.add(PathSelectors.ant(path));
}
// exclude-path处理
List<Predicate<String>> excludePath = new ArrayList<>();
for (String path : swaggerProperties.getExcludePath()) {
excludePath.add(PathSelectors.ant(path));
}
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo)
.groupName(swaggerProperties.getGroup())
.select()
.apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
.paths(Predicates.and(Predicates.not(Predicates.or(excludePath)),Predicates.or(basePath)))
.build();
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
}
复制代码
Common Notes
@Api
Used on classes, this annotation marks a Controller (Class) as a swagger resource (API).
- The tags API groups tags. APIs with the same tag will be grouped together and displayed in one group.
- value If tags are not defined, value will be used as Api tags
@ApiOperation
Describes an operation or HTTP method on the specified (routing) path. Different operations with the same path are grouped into the same operation object.
- value A brief description of the operation, with a length of 120 letters and 60 Chinese characters.
- notes Detailed description of the operation.
- httpMethod HTTP request action name, optional values are: "GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS" and "PATCH".
- code defaults to 200, and valid values must conform to the standard HTTP Status Code Definitions .
@ApiImplicitParams
Used in methods, annotate the container class of ApiImplicitParam and store it in an array.
@ApiImplicitParam
Annotate a single parameter of the API. Although the annotation @ApiParam is bound to JAX-RS parameters, the @ApiImplicitParam annotation can define the parameter list in a unified way, and it is also the only way to define parameters in Servelet and non-JAX-RS environments.
@ApiParam
Added meta-information description for parameters. This annotation can only be used in the integrated environment of JAX-RS 1.x/2.x. Its main properties are
- required 是否为必传参数,默认为false
- value 参数简短说明
@ApiResponses
注解@ApiResponse的包装类,数组结构。即使需要使用一个@ApiResponse注解,也需要将@ApiResponse注解包含在注解@ApiResponses内。
@ApiResponse
描述一个操作可能的返回结果。当REST API请求发生时,这个注解可用于描述所有可能的成功与错误码。可以用,也可以不用这个注解去描述操作的返回类型,但成功操作的返回类型必须在@ApiOperation中定义。如果API具有不同的返回类型,那么需要分别定义返回值,并将返回类型进行关联。但Swagger不支持同一返回码,多种返回类型的注解。注意:这个注解必须被包含在@ApiResponses注解中。
- code HTTP请求返回码。有效值必须符合标准的HTTP Status Code Definitions。
- message 更加易于理解的文本消息
- response 返回类型信息,必须使用完全限定类名,比如“com.xyz.cc.Person.class”。
- responseContainer 如果返回类型为容器类型,可以设置相应的值。有效值为 "List", "Set" or "Map",其他任何无效的值都会被忽略。
@ApiModel
描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
- value model的别名,默认为类名
- description model的详细描述
@ApiModelProperty
描述一个model的属性
- value 属性简短描述
- example 属性的示例值
- required 是否为必须值
若有收获,就点个赞吧