Swwager使用及原理
整理一下,Swagger的使用和原理
Spring Boot 整合Swagger
官方文档与下载
推荐文档
引入依赖
1  | <dependency>  | 
添加Swwager配置类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
41
42
43
44
45
46
2
public class Swagger2Config extends WebMvcConfigurationSupport {
    /**
     * 因为 Swagger2的资源文件都是在jar包里面,如果不在此处配置加载静态资源,
     * 会导致请求http://localhost:8081/swagger-ui.html失败
     *  <!--swagger资源配置-->
     *  <mvc:resources location="classpath:/META-INF/resources/" mapping="swagger-ui.html"/>
     *  <mvc:resources location="classpath:/META-INF/resources/webjars/" mapping="/webjars/**"/>
     *
     * @param registry
     */
    
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
    
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.lx.soilparent.controller"))
                .paths(PathSelectors.any())
                .build()
                //不需要时,或者生产环境可以在此处关闭
                .enable(true);
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("描述:测试使用Swagger2!")
                //服务条款网址
                .termsOfServiceUrl("www.aslan007.github.io")
                .contact("Aslan")
                .version("1.0")
                .build();
    }
}
原理
springfox大致原理
springfox的大致原理就是,在项目启动的过种中,spring上下文在初始化的过程,框架自动跟据配置加载一些swagger相关的bean到当前的上下文中,并自动扫描系统中可能需要生成api文档那些类,并生成相应的信息缓存起来。如果项目MVC控制层用的是springMvc那么会自动扫描所有Controller类,跟据这些Controller类中的方法生成相应的api文档。