Swagger| 源码分析

文章目录

  • swagger入口: @EnableSwagger2
  • Swagger2DocumentationConfiguration
  • SpringfoxWebMvcConfiguration
  • SwaggerCommonConfiguration


swagger入口: @EnableSwagger2

@Configuration
@EnableSwagger2
@PropertySource("classpath:api.properties")
public class SwaggerConfig {

    public static final String API_TILE = "api.title";
    public static final String API_DESC = "api.desc";
    public static final String API_VERSION = "api.version";
    public static final String API_SERVICE_URL = "api.service.url";
    public static final String API_BASE_PATH = "api.base.path";
    public static final String API_HOST = "api.host";

我们可以看到swagger的所有入口就是通过这个注解@EnableSwagger2接下来我们来看一下这个注解做了啥事情

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({Swagger2DocumentationConfiguration.class})
public @interface EnableSwagger2 {
}

@Import用来导入@Configuration注解的配置类,这里我们可以看到通过@Import注解将Swagger2DocumentationConfiguration导入了,接下来我们看一下这个swagger的配置类.


Swagger2DocumentationConfiguration

Swagger2DocumentationConfiguration 为swagger的配置类

@Configuration
@Import({ SpringfoxWebMvcConfiguration.class, SwaggerCommonConfiguration.class })
@ComponentScan(basePackages = {
    "springfox.documentation.swagger2.readers.parameter",
    "springfox.documentation.swagger2.mappers"
})
public class Swagger2DocumentationConfiguration {
  @Bean
  public JacksonModuleRegistrar swagger2Module() {
    return new Swagger2JacksonModule();
  }

  @Bean
  public HandlerMapping swagger2ControllerMapping(
      Environment environment,
      DocumentationCache documentationCache,
      ServiceModelToSwagger2Mapper mapper,
      JsonSerializer jsonSerializer) {
    return new PropertySourcedRequestMappingHandlerMapping(
        environment,
        new Swagger2Controller(environment, documentationCache, mapper, jsonSerializer));
  }
}

Swagger2DocumentationConfiguration做的事情:

  • 构造Bean。比如HandlerMapping,HandlerMapping是springmvc中用于处理请求与handler(controller中的方法)之间映射关系的接口,springboot中默认使用的HandlerMapping是RequestMappingHandlerMapping,Swagger2DocumentationConfiguration配置类里构造的是PropertySourcedRequestMappingHandlerMapping,该类继承RequestMappingHandlerMapping。
  • import其它配置类,比如SpringfoxWebMvcConfiguration、SwaggerCommonConfiguration
  • 扫描指定包下的类,并注册到Spring上下文中

接下来我们仔细看看导入的两个配置类 SpringfoxWebMvcConfiguration,SwaggerCommonConfiguration.

SpringfoxWebMvcConfiguration

SwaggerCommonConfiguration


参考: https://zhuanlan.zhihu.com/p/38245805

你可能感兴趣的:(【Swagger】)