版本 |
作者 |
描述 |
日期 |
V1.0 |
yy |
基于公司现有项目的swagger引入 |
2018-6-5 09:21:02 |
|
|
|
|
|
|
|
|
Swagger是一款让程序自动生成API的开发插件。样式、内容等均可定制化,一般采取默认即可
Java项目通常基于spring,spring也提供了相关中间件和swagger进行集成,使我们用起来更简单。下面则是不同的Spring版本引入swagger的方式
1.在pom中引入:
2.引入config
将这两个文件copy进工程中,能扫描到即可
package com.jinhuhang.settlement.plugins;
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 Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.jinhuhang.settlement.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("settlement api文档")
.description("settlement api文档 测试环境 ")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
}
package com.jinhuhang.settlement.plugins;
import java.nio.charset.Charset;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MvcConfiguration extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index.html");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Bean
public HttpMessageConverter responseBodyConverter() {
StringHttpMessageConverter converter = new StringHttpMessageConverter(
Charset.forName("UTF-8"));
return converter;
}
@Override
public void configureMessageConverters(
List> converters) {
super.configureMessageConverters(converters);
converters.add(responseBodyConverter());
}
@Override
public void configureContentNegotiation(
ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(false);
}
}
MvcConfiguration重点:解析jar包中的视图
3.打开 http://ip:port/项目名/swagger-ui.html
1.maven依赖
2.Swagger配置文件
copy文件至可扫描路径
package com.custom.web.swagger;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static com.google.common.base.Predicates.or;
import static com.google.common.collect.Lists.newArrayList;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration // 配置注解,自动在本类上下文加载一些环境变量信息
@EnableSwagger2 // 使swagger2生效
@EnableWebMvc
@ComponentScan(basePackages = {"com.custom.web"}) //需要扫描的包路径
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket swaggerSpringMvcPlugin() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("business-api")
.select() // 选择那些路径和api会生成document
.apis(RequestHandlerSelectors.basePackage("com.custom.web"))
.paths(paths())
//.apis(RequestHandlerSelectors.any()) // 对所有api进行监控
//.paths(PathSelectors.any()) // 对所有路径进行监控
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private Predicate paths() {
return or(regex("/person.*"));
}
private List securitySchemes() {
return newArrayList(
new ApiKey("clientId", "客户端ID", "header"),
new ApiKey("clientSecret", "客户端秘钥", "header"),
new ApiKey("accessToken", "客户端访问标识", "header"));
}
private List securityContexts() {
return newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/*.*"))
.build()
);
}
List defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return newArrayList(
new SecurityReference("clientId", authorizationScopes),
new SecurityReference("clientSecret", authorizationScopes),
new SecurityReference("accessToken", authorizationScopes));
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring 中使用Swagger2构建RESTful API")
.termsOfServiceUrl("")
.description("此API提供接口调用")
.version("2.0").build();
}
}
要修改的点如下图:
3.web.xml配置说明
说明:Springmvc前端控制器扫描路径增加“/v2/api-docs”,用于扫描Swagger的 /v2/api-docs,否则/v2/api-docs无法生效。
4.spring-mvc.xml 增加自动扫描Swagger
或者
5.访问:http://IP:port/{context-path}/swagger-ui.html
接口api为非业务代码,不建议代码占用太多篇幅。在这里只推荐使用一个标签,这个标签可以代替掉接口上的注释
参数 |
解释 |
@ApiOperation |
接口描述(描述接口是干嘛的,对参数进行说明) |
参数 |
解释 |
@ApiOperation() |
接口描述 |
@ApiParam() |
字段描述 |
@ApiModel() |
类描述(参数是实体类的情况) |
@ApiModelProperty() |
类字段描述(参数是实体类的情况) |
@ApiIgnore() |
类和方法(废弃的方法使用,代表不生成api) |
上图为添加@ApiOperation()的效果图
1>@ApiOperation()中的内容(接口说明)
2>自动生成的返回值(rest接口通常最简洁模式:
{“code”:”是否成功 1是0否”,”
msg”:”消息,失败时显示原因”,
”model”:”返回的内容,为Object类型,根据业务自定义”
}
)
3>自动生成的参数类型
在字段上添加@ApiParam标签后的效果
代码片段如下:
该方式当字段比较多时候,controller方法入参显得过于臃肿,字段较多时可将参数描述放入ApiOperation中
当参数为实体类的情况,点击图中标记 即可赋值到左边文本域。直接进行编辑即可发送情况。
通常入参根据具体业务规范,返回参数规范如下:
字段 |
类型 |
描述 |
code |
Int |
是否成功 1是0否 |
msg |
String |
消息描述 |
Model |
Object |
任意类型参数 |
{“code”:“是否成功 1是0否”,
“msg”:“消息,失败时显示原因”,
“model”:“返回的内容,为Object类型,根据业务自定义”
}
Swagger官网: https://swagger.io/
同类型框架:https://spring.io/projects/spring-restdocs