Springfox和BeanPostProcessor原理分析

springfox 是什么

springfox的前身是swagger-springmvc,用于springmvcswagger的整合

鉴于swagger的强大功能,Java开源界大牛spring框架迅速跟上,它充分利用自已的优势,把swagger集成到自己的项目里,整了一个spring-swagger,后来便演变成springfoxspringfox本身只是利用自身的aop的特点,通过plug的方式把swagger集成了进来,它本身对业务api的生成,还是依靠swagger来实现。 在项目启动过程中,spring上下文初始化时自动跟据配置加载swagger相关的bean到当前上下文中,并自动扫描系统中可能需要生成api文档那些类,并生成相应的信息缓存起来。如果项目MVC控制层用的是springMvc那么会自动扫描所有Controller类,跟据这些Controller类中的方法生成相应的api文档。

如若在springboot项目中使用springfox,需要3个步骤:

  1. maven添加springfox依赖

  2. 启动类加上@EnableSwagger2注解

  3. 构造Docket bean用于展示API

配置完之后进入http://{path}:{port}/swagger-ui.html 即可查看controller中的接口信息,并按照Docket中配置的规则进行展示。

springfox如何定义Documentation:

springfox

文档Documentation定义得很清晰,主要由groupName(分组名)、basePath(contextPath)、apiListings(API列表集)、resourceListing(资源列表集)等属性组成。

其中API列表被封装成ApiListing。ApiListing中又持有ApiDesciption集合引用,每个ApiDesciption都持有一个API集合的引用,Operation也就是具体的接口操作,内部包含了该接口对应的http方法、produces、consumes、协议、参数集、响应消息集等诸多元素。

springfox通过spring-plugin的方式将Plugin注册到Spring上下文中,然后使用这些plugin进行API的扫描工作,这里的扫描工作其实也就是构造Documentation的工作,把扫描出的结果封装成Documentation并放入到DocumentationCache内存缓存中,之后swagger-ui界面展示的API信息通过Swagger2Controller暴露,Swagger2Controller内部直接从DocumentationCache中寻找Documentation。

下图就是部分Plugin具体构造对应的文档信息:

plugin

代码细节方面的分析:

很明显,入口处在@EnableSwagger2注解上,该注解会import一个配置类Swagger2DocumentationConfiguration。

Swagger2DocumentationConfiguration做的事情:

  1. 构造Bean。比如HandlerMapping,HandlerMapping是springmvc中用于处理请求与handler(controller中的方法)之间映射关系的接口,springboot中默认使用的HandlerMapping是RequestMappingHandlerMapping,Swagger2DocumentationConfiguration配置类里构造的是PropertySourcedRequestMappingHandlerMapping,该类继承RequestMappingHandlerMapping。

  2. import其它配置类,比如SpringfoxWebMvcConfiguration、SwaggerCommonConfiguration

  3. 扫描指定包下的类,并注册到Spring上下文中

SpringfoxWebMvcConfiguration配置类做的事情跟Swagger2DocumentationConfiguration类似,不过多了一步构造PluginRegistry过程。该过程使用@EnablePluginRegistries注解实现:

@EnablePluginRegistries({ DocumentationPlugin.class,
    ApiListingBuilderPlugin.class,
    OperationBuilderPlugin.class,
    ParameterBuilderPlugin.class,
    ExpandedParameterBuilderPlugin.class,
    ResourceGroupingStrategy.class,
    OperationModelsProviderPlugin.class,
    DefaultsProviderPlugin.class,
    PathDecorator.class,
    ApiListingScannerPlugin.class
})

@EnablePluginRegistries注解是spring-plugin模块提供的一个基于Plugin类型注册PluginRegistry实例到Spring上下文的注解。

@EnablePluginRegistries注解内部使用PluginRegistriesBeanDefinitionRegistrar注册器去获取注解的value属性(类型为Plugin接口的Class数组);然后遍历这个Plugin数组,针对每个Plugin在Spring上下文中注册PluginRegistryFactoryBean,并设置相应的name和属性。

如果处理的Plugin有@Qualifier注解,那么这个要注册的PluginRegistryFactoryBean的name就是@Qualifier注解的value,否则name就是插件名首字母小写+Registry的格式(比如DocumentationPlugin对应构造的bean的name就是documentationPluginRegistry)。

PluginRegistriesBeanDefinitionRegistrar注册器处理过程:

@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

   Class[] types = (Class[]) importingClassMetadata.getAnnotationAttributes(
         EnablePluginRegistries.class.getName()).get("value");

   for (Class type : types) {

      BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(PluginRegistryFactoryBean.class);
      builder.addPropertyValue("type", type);

      AbstractBeanDefinition beanDefinition = builder.getBeanDefinition();
      Qualifier annotation = type.getAnnotation(Qualifier.class);

      // If the plugin interface has a Qualifier annotation, propagate that to the bean definition of the registry
      if (annotation != null) {
         AutowireCandidateQualifier qualifierMetadata = new AutowireCandidateQualifier(Qualifier.class);
         qualifierMetadata.setAttribute(AutowireCandidateQualifier.VALUE_KEY, annotation.value());
         beanDefinition.addQualifier(qualifierMetadata);
      }

      // Default
      String beanName = annotation == null ? StringUtils.uncapitalize(type.getSimpleName() + "Registry") : annotation
            .value();
      registry.registerBeanDefinition(beanName, builder.getBeanDefinition());
   }
}

PluginRegistryFactoryBean是一个FactoryBean,其内部真正构造的bean的类型是OrderAwarePluginRegistry。OrderAwarePluginRegistry实例化过程中会调用create静态方法,传入的plugin集合使用aop代理生成一个ArrayList,这个list中的元素就是Spring上下文中所有的类型为之前遍历的Plugin的bean。 PluginRegistryFactoryBean的getObject方法:

public OrderAwarePluginRegistry getObject() {
   return OrderAwarePluginRegistry.create(getBeans());
}
protected List getBeans() {
   ProxyFactory factory = new ProxyFactory(List.class, targetSource);
   return (List) factory.getProxy();
}

这里的targetSource是在PluginRegistryFactoryBean的父类AbstractTypeAwareSupport(实现了InitializingBean接口)中的afterPropertiesSet方法中初始化的(type属性在PluginRegistriesBeanDefinitionRegistrar注册器中已经设置为遍历的Plugin):

public void afterPropertiesSet() {
   this.targetSource = new BeansOfTypeTargetSource(context, type, false, exclusions);
}

BeansOfTypeTargetSource的getTarget方法:

public synchronized Object getTarget() throws Exception {
   Collection components = this.components == null ? getBeansOfTypeExcept(type, exclusions)
         : this.components;

   if (frozen && this.components == null) {
      this.components = components;
   }

   return new ArrayList(components);
}

private Collection getBeansOfTypeExcept(Class type, Collection> exceptions) {
  List result = new ArrayList();

  for (String beanName : context.getBeanNamesForType(type, false, eagerInit)) {
    if (exceptions.contains(context.getType(beanName))) {
      continue;
    }
    result.add(context.getBean(beanName));
  }

  return result;
}

举个例子:比如SpringfoxWebMvcConfiguration中的@EnablePluginRegistries注解里的DocumentationPlugin这个Plugin,在处理过程中会找出Spring上下文中所有的Docket(Docket实现了DocumentationPlugin接口),并把该集合设置成name为documentationPluginRegistry、类型为OrderAwarePluginRegistry的bean,注册到Spring上下文中。

DocumentationPluginsManager类会在之前提到过的配置类中被扫描出来,它内部的各个pluginRegistry属性都是@EnablePluginRegistries注解内部构造的各种pluginRegistry实例:

@Component
public class DocumentationPluginsManager {
  @Autowired
  @Qualifier("documentationPluginRegistry")
  private PluginRegistry documentationPlugins;
  @Autowired
  @Qualifier("apiListingBuilderPluginRegistry")
  private PluginRegistry apiListingPlugins;
  @Autowired
  @Qualifier("parameterBuilderPluginRegistry")
  private PluginRegistry parameterPlugins;
  ...
}

DocumentationPluginsBootstrapper启动类也会在之前提供的配置类中被扫描出来。它实现了SmartLifecycle接口,在start方法中,会获取之前初始化的所有documentationPlugins(也就是Spring上下文中的所有Docket)。遍历这些Docket并进行scan扫描(使用RequestMappingHandlerMapping的getHandlerMethods方法获取url与方法的所有映射关系,然后进行一系列API解析操作),扫描出来的结果封装成Documentation并添加到DocumentationCache中:

@Override
public void start() {
  if (initialized.compareAndSet(false, true)) {
    log.info("Context refreshed");
    List plugins = pluginOrdering()
        .sortedCopy(documentationPluginsManager.documentationPlugins());
    log.info("Found {} custom documentation plugin(s)", plugins.size());
    for (DocumentationPlugin each : plugins) {
      DocumentationType documentationType = each.getDocumentationType();
      if (each.isEnabled()) {
        scanDocumentation(buildContext(each));
      } else {
        log.info("Skipping initializing disabled plugin bean {} v{}",
            documentationType.getName(), documentationType.getVersion());
      }
    }
  }
}
springfox

下面分析一下HandlerMapping的处理过程
PropertySourcedRequestMappingHandlerMapping在Swagger2DocumentationConfiguration配置类中被构造:

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

PropertySourcedRequestMappingHandlerMapping初始化过程中会设置优先级为Ordered.HIGHEST_PRECEDENCE + 1000,同时还会根据Swagger2Controller得到RequestMappingInfo映射信息,并设置到handlerMethods属性中。

PropertySourcedRequestMappingHandlerMapping复写了lookupHandlerMethod方法,首先会去handlerMethods属性中查询是否存在对应的映射关系,没找到的话使用下一个HandlerMapping进行处理:

@Override
protected HandlerMethod lookupHandlerMethod(String urlPath, HttpServletRequest request) throws Exception {
  logger.debug("looking up handler for path: " + urlPath);
  HandlerMethod handlerMethod = handlerMethods.get(urlPath);
  if (handlerMethod != null) {
    return handlerMethod;
  }
  for (String path : handlerMethods.keySet()) {
    UriTemplate template = new UriTemplate(path);
    if (template.matches(urlPath)) {
      request.setAttribute(
          HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE,
          template.match(urlPath));
      return handlerMethods.get(path);
    }
  }
  return null;
}

Swagger2Controller中只有一个mapping方法,默认的path值为/v2/api-docs,可以通过配置 springfox.documentation.swagger.v2.path 进行修改。所以默认情况下 /v2/api-docs?group=person-api、/v2/api-docs?group=user-api 这些地址都会被Swagger2Controller所处理。

Swagger2Controller内部获取文档信息会去DocumentationCache中查找:

@RequestMapping(
    value = DEFAULT_URL,
    method = RequestMethod.GET,
    produces = { APPLICATION_JSON_VALUE, HAL_MEDIA_TYPE })
@PropertySourcedMapping(
    value = "${springfox.documentation.swagger.v2.path}",
    propertyKey = "springfox.documentation.swagger.v2.path")
@ResponseBody
public ResponseEntity getDocumentation(
    @RequestParam(value = "group", required = false) String swaggerGroup,
    HttpServletRequest servletRequest) {

  String groupName = Optional.fromNullable(swaggerGroup).or(Docket.DEFAULT_GROUP_NAME);
  Documentation documentation = documentationCache.documentationByGroup(groupName);
  if (documentation == null) {
    return new ResponseEntity(HttpStatus.NOT_FOUND);
  }
  Swagger swagger = mapper.mapDocumentation(documentation);
  UriComponents uriComponents = componentsFrom(servletRequest, swagger.getBasePath());
  swagger.basePath(Strings.isNullOrEmpty(uriComponents.getPath()) ? "/" : uriComponents.getPath());
  if (isNullOrEmpty(swagger.getHost())) {
    swagger.host(hostName(uriComponents));
  }
  return new ResponseEntity(jsonSerializer.toJson(swagger), HttpStatus.OK);
}

引入springfox带来的影响

影响主要有2点:

  1. 应用启动速度变慢,因为额外加载了springfox中的信息,同时内存中也缓存了这些API信息

  2. 多了一个HandlerMapping,并且优先级高。其中springfox构造的PropertySourcedRequestMappingHandlerMapping优先级最高。优先级最高说明第一次查询映射关系都是走PropertySourcedRequestMappingHandlerMapping,而程序中大部分请求Path路径都映射到RequestMappingHandlerMapping中处理的,所以进入到PropertySourcedRequestMappingHandlerMapping处理的请求会报:

    did not find handler

    而默认的path值为/v2/api-docs则会成功处理:
    success-find-handler

    以下是springboot应用DispatcherServlet的HandlerMapping集合:

PropertySourcedRequestMappingHandlerMapping

优先级问题可以使用BeanPostProcessor处理,修改优先级:

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    if(beanName.equals("swagger2ControllerMapping")) {
        ((PropertySourcedRequestMappingHandlerMapping) bean).setOrder(Ordered.LOWEST_PRECEDENCE - 1000);
    }
    return bean;
}

以上内容转载自:知乎


BeanPostProcessor是什么

BeanPostProcessor接口作用是:如果我们需要在Spring容器完成Bean的实例化、配置和其他的初始化前后添加一些自己的逻辑处理,我们就可以定义一个或者多个BeanPostProcessor接口的实现,然后注册到容器中。

Spring中Bean的实例化过程图示:

BeanPostProcessor

由上图可以看到,Spring中的BeanPostProcessor在实例化过程处于的位置,BeanPostProcessor接口有两个方法需要实现:postProcessBeforeInitialization和postProcessAfterInitialization

import org.springframework.beans.factory.config.BeanPostProcessor;  

//让Spring加载到该类
@Component
public class MyBeanPostProcessor implements BeanPostProcessor {  

     public MyBeanPostProcessor() {  
        super();  
        System.out.println("这是BeanPostProcessor实现类构造器!!");          
     }  

     @Override  
     public Object postProcessAfterInitialization(Object bean, String arg1)  
             throws BeansException {  
         System.out.println("bean处理器:bean创建之后..");  
         return bean;  
     }  

     @Override  
     public Object postProcessBeforeInitialization(Object bean, String arg1)  
             throws BeansException {  
         System.out.println("bean处理器:bean创建之前..");  

         return bean;  
     }  
 }

BeanPostProcessor接口定义如下:

public interface BeanPostProcessor {  

    /** 
     * Apply this BeanPostProcessor to the given new bean instance before any bean 
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet} 
     * or a custom init-method). The bean will already be populated with property values.    
     */  
//实例化、依赖注入完毕,在调用显示的初始化之前完成一些定制的初始化任务  
    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;  

    /** 
     * Apply this BeanPostProcessor to the given new bean instance after any bean 
     * initialization callbacks (like InitializingBean's {@code afterPropertiesSet}   
     * or a custom init-method). The bean will already be populated with property values.       
     */  
//实例化、依赖注入、初始化完毕时执行  
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;  

}

由方法名字也可以看出,前者在实例化及依赖注入完成后、在任何初始化代码(比如配置文件中的init-method)调用之前调用;后者在初始化代码调用之后调用。

注意:

1、接口中的两个方法都要将传入的bean返回,而不能返回null,如果返回的是null那么我们通过getBean方法将得不到目标。

2、BeanFactory和ApplicationContext对待bean后置处理器稍有不同。ApplicationContext会自动检测在配置文件中实现了BeanPostProcessor接口的所有bean,并把它们注册为后置处理器,然后在容器创建bean的适当时候调用它,因此部署一个后置处理器同部署其他的bean并没有什么区别。而使用BeanFactory实现的时候,bean 后置处理器必须通过代码显式地去注册,在IoC容器继承体系中的ConfigurableBeanFactory接口中定义了注册方法:

/**  
 * Add a new BeanPostProcessor that will get applied to beans created  
 * by this factory. To be invoked during factory configuration.  
 * 

另外,不要将BeanPostProcessor标记为延迟初始化。因为如果这样做,Spring容器将不会注册它们,自定义逻辑也就无法得到应用。假如你在<beans />元素的定义中使用了'default-lazy-init'属性,请确信你的各个BeanPostProcessor标记为'lazy-init="false"'。

InstantiationAwareBeanPostProcessor

InstantiationAwareBeanPostProcessor是BeanPostProcessor的子接口,可以在Bean生命周期的另外两个时期提供扩展的回调接口,即实例化Bean之前(调用postProcessBeforeInstantiation方法)和实例化Bean之后(调用postProcessAfterInstantiation方法),该接口定义如下:

package org.springframework.beans.factory.config;    

import java.beans.PropertyDescriptor;    

import org.springframework.beans.BeansException;    
import org.springframework.beans.PropertyValues;    

public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {    

    Object postProcessBeforeInstantiation(Class beanClass, String beanName) throws BeansException;    

    boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;    

    PropertyValues postProcessPropertyValues(    
            PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)    
            throws BeansException;    

}

其使用方法与上面介绍的BeanPostProcessor接口类似,只时回调时机不同。

如果是使用ApplicationContext来生成并管理Bean的话则稍有不同,使用ApplicationContext来生成及管理Bean实例的话,在执行BeanFactoryAware的setBeanFactory()阶段后,若Bean类上有实现org.springframework.context.ApplicationContextAware接口,则执行其setApplicationContext()方法,接着才执行BeanPostProcessors的ProcessBeforeInitialization()及之后的流程。

以上内容转载自:CSDN

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容