一、背景介绍
当我们在开发API时,通常需要编写API文档以便其他人可以使用我们的API。这通常需要花费大量时间和精力来编写和维护。Swagger2就是为了解决这个问题而生的。
Swagger2是一种用于API文档编写和测试的框架,它可以通过自动生成文档来简化API设计和开发工作。使用Swagger2,我们可以不必手动编写API文档,而是可以通过注解自动生成API文档。
二、什么是Swagger2
Swagger2是一种用于API文档编写和测试的框架,它可以通过自动生成文档来简化API设计和开发工作。Swagger2支持多种语言,包括Java、C#、Python等等。在Java中,我们可以使用Swagger2注解来编写API文档。
三、常用注解
Swagger2支持多种注解,以下是一些常用的注解:
3.1 @Api
用于类上,表示该类是一个API资源类。
3.2 @ApiOperation
用于方法上,表示一个HTTP请求的操作。
3.3 @ApiParam
用于参数上,用来描述参数的信息。
3.4 @ApiModel
用于类上,表示该类是一个Swagger2的数据模型。
3.5 @ApiModelProperty
用于属性上,表示一个Swagger2的数据模型属性。
四、SpringBoot整合Swagger2
在SpringBoot中,我们可以使用Swagger2来自动生成API文档。以下是整合Swagger2的步骤:
4.1 添加Swagger2依赖
在pom.xml文件中添加以下依赖:
<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>
4.2 添加Swagger2配置类
在SpringBoot项目中添加一个Swagger2的配置类:
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API文档")
.description("这是一个API文档")
.version("1.0")
.build();
}
}
在上面的代码中,我们创建了一个Docket对象来配置Swagger2。我们指定了API文档的标题、描述和版本,还指定了API的扫描包路径和API的路径。
4.3 运行项目
在运行SpringBoot项目之后,我们可以通过访问http://localhost:8080/swagger-ui.html来查看自动生成的API文档。
五、生产环境下屏蔽Swagger2
在生产环境下,我们通常不希望暴露Swagger2的API文档。以下是屏蔽Swagger2的方法:
5.1 修改Swagger2配置类
在Swagger2配置类中添加以下代码:
@Bean
@Profile({"dev", "test"})
public Docket createRestApi() {
// ...
}
@Bean
@Profile("prod")
public Docket createProdRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.none())
.paths(PathSelectors.none())
.build();
}
在上面的代码中,我们添加了一个名为createProdRestApi的Docket对象,用于生产环境下屏蔽Swagger2。当SpringBoot的环境变量为"prod"时,会自动加载createProdRestApi方法,该方法会屏蔽所有的API文档。
5.2 修改application.yml
在application.yml文件中添加以下配置:
spring:
profiles:
active: prod
在上面的配置中,我们指定了SpringBoot的环境变量为"prod",这样就可以屏蔽Swagger2的API文档。
六、使用maven package打包测试
在开发过程中,我们可以使用maven package命令打包项目并进行测试。以下是打包和测试的步骤:
6.1 打包项目
在项目的根目录下,输入以下命令:
mvn package
这条命令会将项目打包成一个jar包,位于target目录下。
6.2 运行项目
在target目录下,输入以下命令:
java -jar demo-0.0.1-SNAPSHOT.jar
该命令会启动SpringBoot项目,并可以通过访问http://localhost:8080/swagger-ui.html来查看自动生成的API文档。
七、其他扩展点
除了上述内容,还有一些其他扩展点可以帮助我们更好地使用Swagger2:
7.1 配置全局参数
我们可以通过以下代码来配置全局参数:
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(
Arrays.asList(
new ParameterBuilder()
.name("Authorization")
.description("用户认证token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(false)
.build()
)
)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
在上面的代码中,我们添加了一个全局参数Authorization,表示用户认证token。
7.2 配置安全认证
我们可以通过以下代码来配置安全认证:
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.securitySchemes(Arrays.asList(apiKey()))
.securityContexts(Arrays.asList(securityContext()))
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiKey apiKey() {
return new ApiKey("token", "token", "header");
}
private SecurityContext securityContext() {
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("/*.*"))
.build();
}
private List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Arrays.asList(new SecurityReference("token", authorizationScopes));
}
在上面的代码中,我们添加了一个安全认证方式token,并配置了安全上下文和安全引用。
7.3 配置文档分组
我们可以通过以下代码来配置文档分组:
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("group1")
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build();
}
在上面的代码中,我们添加了一个文档分组group1,表示该API文档属于group1分组。可以通过访问http://localhost:8080/swagger-ui.html来查看自动生成的API文档。
7.4 配置插件
我们可以通过以下代码来配置插件:
<build>
<plugins>
<plugin>
<groupId>com.github.kongchen</groupId>
<artifactId>swagger-maven-plugin</artifactId>
<version>3.1.8</version>
<configuration>
<apiSources>
<apiSource>
<locations>
<location>com.example.controller</location>
</locations>
<swaggerDirectory>${project.build.directory}/swagger-ui</swaggerDirectory>
<basePath>/api</basePath>
<info>
<title>API文档</title>
<version>1.0</version>
<description>这是一个API文档</description>
</info>
</apiSource>
</apiSources>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
在上面的代码中,我们添加了一个名为swagger-maven-plugin的插件,用于自动生成API文档。该插件可以根据指定的包路径和配置信息自动生成API文档,并保存在指定的目录下。
7.5 配置国际化
我们可以通过以下代码来配置国际化:
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.controller"))
.paths(PathSelectors.any())
.build()
.directModelSubstitute(LocalDate.class, String.class)
.genericModelSubstitutes(ResponseEntity.class)
.alternateTypeRules(
newRule(typeResolver.resolve(DeferredResult.class,
typeResolver.resolve(ResponseEntity.class, WildcardType.class)),
typeResolver.resolve(WildcardType.class)))
.useDefaultResponseMessages(false)
.globalResponseMessage(RequestMethod.GET,
newArrayList(new ResponseMessageBuilder()
.code(500)
.message("500 message")
.responseModel(new ModelRef("Error"))
.build(),
new ResponseMessageBuilder()
.code(403)
.message("Forbidden!")
.build()))
.securitySchemes(newArrayList(apiKey()))
.securityContexts(newArrayList(securityContext()))
.enableUrlTemplating(true)
.globalOperationParameters(
newArrayList(new ParameterBuilder()
.name("someGlobalParameter")
.description("Description of someGlobalParameter")
.modelRef(new ModelRef("string"))
.parameterType("query")
.required(false)
.build()))
.tags(new Tag("Pet Service", "All apis relating to pets"));
}
在上面的代码中,我们添加了一些国际化配置,包括替换日期类型、替换响应类型、替换类型规则、使用默认响应消息、全局响应消息、安全方案、安全上下文、启用URL模板、全局操作参数和API标签。
八、总结
在本文中,我们介绍了Swagger2的基本概念和常用注解,以及如何在SpringBoot中整合Swagger2。我们还介绍了如何在生产环境下屏蔽Swagger2,以及一些其他的扩展点,包括配置全局参数、安全认证、文档分组、插件和国际化。希望本文对大家了解Swagger2有所帮助。
文章评论