Swagger| 源码分析


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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值