背景
项目中简洁的页面后端API测试工具,会大大提升开发效率,这里使用SpringBoot + Swagger来实现。
步骤
- 添加依赖
# gradle
implementation('io.springfox:springfox-swagger2:2.6.1')
implementation('io.springfox:springfox-swagger-ui:2.6.1')
# maven
<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>
- 添加配置类SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 添加待扫描包名
.apis(RequestHandlerSelectors.basePackage("Replace me with a package name"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 添加描述信息
.title("I am a title")
.description("I am a description")
.version("1.0.0")
.build();
}
}
- 对Controller接口注解
@ApiOperation(value = "Interface name", notes = "What the interface do")
备注
如果在SpringMVC中使用,需要在配置文件中添加如下配置。
<mvc:default-servlet-handler />
<mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />
<mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
<bean id="swaggerConfig" class="com.rainlf.config.SwaggerConfig"/>
网友评论