tonglin0325的个人主页

SpringBoot学习笔记——swagger-ui

swagger-ui用于给API添加文档,还支持API的请求调用,可以降低前后端联调的沟通成本

1.依赖

1
2
3
4
5
6
7
8
9
10
11
12
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>

2.配置swagger,注意修改basePackage成实际的包名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.async.DeferredResult;
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 SwaggerConfig {

@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.genericModelSubstitutes(DeferredResult.class)
.useDefaultResponseMessages(false)
.forCodeGeneration(true)
.apiInfo(apiInfo())
.pathMapping("/") // base,最终调用接口后会和paths拼接在一起
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo")) // 过滤的接口
.paths(PathSelectors.any())
.build();
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("api文档") // 标题
.description("xxxx") // 描述
.termsOfServiceUrl("https://xxx.xxx.xxx")
.version("1.0")
.build();
}

}

3.给controller添加
 ApiOperation 注解

1
2
3
4
5
6
@ApiOperation(value = "hello接口", notes = "取得id,打印hello")
@RequestMapping(path = "/hello/{id}", method = RequestMethod.GET)
public ControllerResponseT hello(@ApiParam(name = "id", value = "id", required = true) @PathVariable("id") Integer id) {
return ControllerResponseT.ofSuccess("hello: " + id);
}

4.测试

 

如果在添加了统一的接口返回值配置之后出现swagger-ui.html 404,需要额外添加如下配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebAppConfig implements WebMvcConfigurer {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/public/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}