Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor

这篇具有很好参考价值的文章主要介绍了Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Spring源码系列文章

Spring源码解析(一):环境搭建

Spring源码解析(二):bean容器的创建、默认后置处理器、扫描包路径bean

Spring源码解析(三):bean容器的刷新

Spring源码解析(四):单例bean的创建流程

Spring源码解析(五):循环依赖

Spring源码解析(六):bean工厂后置处理器ConfigurationClassPostProcessor

Spring源码解析(七):bean后置处理器AutowiredAnnotationBeanPostProcessor

Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor

Spring源码解析(九):AOP源码之@Aspect所有相关注解解析

Spring源码解析(十):spring整合mybatis源码

Spring源码解析(十一):spring事务配置类源码

Spring源码解析(十二):TransactionInterceptor事务拦截器


一、CommonAnnotationBeanPostProcessor简介

主要类图如下:

Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor,spring,spring,java,后端

  • MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
    • 查找bean的@Resource属性和@PostConstruct和@PreDestroy方法并缓存起来
  • InstantiationAwareBeanPostProcessor#postProcessProperties
    • @Resource注解属性填充
  • BeanPostProcessor#postProcessBeforeInitialization
    • 初始化前执行解析@PostConstruct注解的初始化方法
  • DestructionAwareBeanPostProcessor#postProcessBeforeDestruction
    • 销毁前执行解析@PreDestroy主键的销毁方法

二、postProcessMergedBeanDefinition(查询注解信息)

  • 执行时机:实例化之后会调用所有MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition方法
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName){
    //查询@PostConstruct和@PreDestroy`注解并缓存
	super.postProcessMergedBeanDefinition(beanDefinition, beanType, beanName);
	//查询@Resource注解并缓存 
	InjectionMetadata metadata = findResourceMetadata(beanName, beanType, null);
	metadata.checkConfigMembers(beanDefinition);
}

1、查询@PostConstruct和@PreDestroy注解

  • 先从缓存lifecycleMetadataCache中获取
  • 找不到则通过buildLifecycleMetadata构建生命周期元数据,并放入缓存
  • 生命周期元数据,即初始化销毁方法的元数据
private LifecycleMetadata findLifecycleMetadata(Class<?> clazz) {
	// 先查缓存中有没有初始化销毁方法元数据
	// lifecycleMetadataCache是一个map集合,它的key就是当前类的clazz
	// value是当前类初始化销毁方法元数据
	if (this.lifecycleMetadataCache == null) {
		// 如果缓存中没有,则去查询注解构建对应元数据
		return buildLifecycleMetadata(clazz);
	}
	// Quick check on the concurrent map first, with minimal locking.
	LifecycleMetadata metadata = this.lifecycleMetadataCache.get(clazz);
	if (metadata == null) {
		synchronized (this.lifecycleMetadataCache) {
			metadata = this.lifecycleMetadataCache.get(clazz);
			if (metadata == null) {
				// 如果缓存中没有,则去查询注解构建对应元数据
				metadata = buildLifecycleMetadata(clazz);
				//放入缓存,key就是当前类的clazz
				this.lifecycleMetadataCache.put(clazz, metadata);
			}
			return metadata;
		}
	}
	return metadata;
}

CommonAnnotationBeanPostProcessor的构造方法

Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor,spring,spring,java,后端

构建生命周期元数据

  • AnnotationUtils.isCandidateClass()是判断clazz中是否存在@PostConstruct@PreDestroy注解
  • 遍历clazz父类的所有方法,获取@PostConstruct和@PreDestroy注解信息
    • 都将method封装成LifecycleElement
    • 分别放入initMethods和destroyMethods集合中
private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
     /**
      * this.initAnnotationType为PostConstruct.class
      * this.destroyAnnotationType为PreDestroy.class
      * 在CommonAnnotationBeanPostProcessor默认的构造方法中赋值
      * AnnotationUtils.isCandidateClass()是判断clazz中是否存在PostConstruct和PreDestroy注解
      */
   if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
       //不存在PostConstruct和PreDestroy注解,直接返回一个空的生命周期元数据
      return this.emptyLifecycleMetadata;
   }

   List<LifecycleElement> initMethods = new ArrayList<>();
   List<LifecycleElement> destroyMethods = new ArrayList<>();
   Class<?> targetClass = clazz;

   do {
      final List<LifecycleElement> currInitMethods = new ArrayList<>();
      final List<LifecycleElement> currDestroyMethods = new ArrayList<>();

       
     /**
      * ReflectionUtils.doWithLocalMethods()方法很简单
      * 遍历targetClass所有的方法,将它作为参数回调接口方法
      */
      ReflectionUtils.doWithLocalMethods(targetClass, method -> {
		  /****************************处理@PostConstruct注解******************************/         
          //method.isAnnotationPresent()判断方法上有没有指定的注解(反射的知识)
         if (this.initAnnotationType != null && method.isAnnotationPresent(this.initAnnotationType)) {
             //(1)构建LifecycleElement
            LifecycleElement element = new LifecycleElement(method);
             //加入到初始化方法集合中
            currInitMethods.add(element);
            if (logger.isTraceEnabled()) {
               logger.trace("Found init method on class [" + clazz.getName() + "]: " + method);
            }
         }
         /****************************处理@PreDestroy注解******************************/             
         if (this.destroyAnnotationType != null && method.isAnnotationPresent(this.destroyAnnotationType)) {
            currDestroyMethods.add(new LifecycleElement(method));
            if (logger.isTraceEnabled()) {
               logger.trace("Found destroy method on class [" + clazz.getName() + "]: " + method);
            }
         }
      });

      initMethods.addAll(0, currInitMethods);
      destroyMethods.addAll(currDestroyMethods);
       //获取父类,因为父类中也有可能指定了生命周期方法
      targetClass = targetClass.getSuperclass();
   }
   while (targetClass != null && targetClass != Object.class);

    //返回声明周期元数据
   return (initMethods.isEmpty() && destroyMethods.isEmpty() ? this.emptyLifecycleMetadata :
           //(2)构建LifecycleMetadata
         new LifecycleMetadata(clazz, initMethods, destroyMethods));
}

2、查询@Resource注解

  • 与查询生命周期元数据一样,先从缓存中获取,找不到构建
private InjectionMetadata findResourceMetadata(String beanName, final Class<?> clazz, @Nullable PropertyValues pvs) {
    // Fall back to class name as cache key, for backwards compatibility with custom callers.
    String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
    // Quick check on the concurrent map first, with minimal locking.
    InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
    //判断是否需要重新解析clazz
    if (InjectionMetadata.needsRefresh(metadata, clazz)) {
        synchronized (this.injectionMetadataCache) {
            metadata = this.injectionMetadataCache.get(cacheKey);
            if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                if (metadata != null) {
                    metadata.clear(pvs);
                }
                //解析clazz,构建注入@Resource注解元数据
                metadata = buildResourceMetadata(clazz);
                this.injectionMetadataCache.put(cacheKey, metadata);
            }
        }
    }
    return metadata;
}

CommonAnnotationBeanPostProcessor的静态方法

Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor,spring,spring,java,后端

构建@Resource元数据

  • 先判断clazz是否存在@Resource注解,没有则返回空对象
  • 静态方法属性上添加@Resource注解会抛异常,添加@Autowired注解则是不处理不报错
  • 忽略注入的方法属性类型:ignoredResourceTypes=“javax.xml.ws.WebServiceContext
  • @Resource注解只能加载单个参数的方法上
private InjectionMetadata buildResourceMetadata(final Class<?> clazz) {
    //判断clazz是否包含resourceAnnotationTypes中的注解
    if (!AnnotationUtils.isCandidateClass(clazz, resourceAnnotationTypes)) {
        return InjectionMetadata.EMPTY;
    }

    List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
    Class<?> targetClass = clazz;

    do {
        final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
        
		/********************************处理属性*********************************/
        ReflectionUtils.doWithLocalFields(targetClass, field -> {
            //webServiceRef相关,不用管
            if (webServiceRefClass != null && field.isAnnotationPresent(webServiceRefClass)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@WebServiceRef annotation is not supported on static fields");
                }
                currElements.add(new WebServiceRefElement(field, field, null));
            }
            //ejb相关,不用管
            else if (ejbClass != null && field.isAnnotationPresent(ejbClass)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@EJB annotation is not supported on static fields");
                }
                currElements.add(new EjbRefElement(field, field, null));
            }
            //这里开始处理有@Resource注解的属性了
            else if (field.isAnnotationPresent(Resource.class)) {
                //@Resource不能加载静态属性上
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException("@Resource annotation is not supported on static fields");
                }
                //忽略注入的属性类型:ignoredResourceTypes="javax.xml.ws.WebServiceContext"
                if (!this.ignoredResourceTypes.contains(field.getType().getName())) {
                    //构建ResourceElement对象加入到currElements集合中
                    //我们看一下ResourceElement的构造方法
                    currElements.add(new ResourceElement(field, field, null));
                }
            }
        });
        
		/********************************处理方法*********************************/
        ReflectionUtils.doWithLocalMethods(targetClass, method -> {
            //获取桥接方法,你就把它当成一个普通的方法对象
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                return;
            }
            //webServiceRef相关,不用管
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (webServiceRefClass != null && bridgedMethod.isAnnotationPresent(webServiceRefClass)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException("@WebServiceRef annotation is not supported on static methods");
                    }
                    if (method.getParameterCount() != 1) {
                        throw new IllegalStateException("@WebServiceRef annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new WebServiceRefElement(method, bridgedMethod, pd));
                }
                //ejb相关,不用管
                else if (ejbClass != null && bridgedMethod.isAnnotationPresent(ejbClass)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException("@EJB annotation is not supported on static methods");
                    }
                    if (method.getParameterCount() != 1) {
                        throw new IllegalStateException("@EJB annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new EjbRefElement(method, bridgedMethod, pd));
                }
                 //这里开始处理有@Resource注解的方法了
                else if (bridgedMethod.isAnnotationPresent(Resource.class)) {
                    //@Resource不能加载静态方法上
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException("@Resource annotation is not supported on static methods");
                    }
                    //获取方法所有参数的类型
                    Class<?>[] paramTypes = method.getParameterTypes();
                    //@Resource注解只能加载单参数的方法上
                    if (paramTypes.length != 1) {
                        throw new IllegalStateException("@Resource annotation requires a single-arg method: " + method);
                    }
                    //忽略参数名字为javax.xml.ws.WebServiceContext的方法
                    if (!this.ignoredResourceTypes.contains(paramTypes[0].getName())) {
                        /**
                         * 该方法在@Autowired注解原理的时候已经说过了
                         * 就是判断当前方法是不是clazz类某个属性的get或set方法,如果是,就
                         * 返回这个属性的属性描述
                         */
                        PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                        //构建ResourceElement对象加入到currElements集合中
                        currElements.add(new ResourceElement(method, bridgedMethod, pd));
                    }
                }
            }
        });

        elements.addAll(0, currElements);
        //接着去找父类的@Resource注解
        targetClass = targetClass.getSuperclass();
    }
    while (targetClass != null && targetClass != Object.class);

    //构建InjectionMetadata
    return InjectionMetadata.forElements(elements, clazz);
}

ResourceElement的构造方法

  • 获取@Resource注解的name和type属性值
  • name默认值:字段名称/方法去掉set,然后将首字母转小写
  • type如果填写类型,会与注入字段类型做校验
public ResourceElement(Member member, AnnotatedElement ae, @Nullable PropertyDescriptor pd) {
	 super(member, pd);
	 //获取@Resource注解信息
	 Resource resource = ae.getAnnotation(Resource.class);
	 //获取注解name属性值
	 String resourceName = resource.name();
	 //获取注解type属性值
	 Class<?> resourceType = resource.type();
	 /**
     * this.isDefaultName表示是否使用默认名
     * 注解name属性值为空的时候,就表示使用默认名
     * 属性的名字或者方法名截取后的值
     */
    this.isDefaultName = !StringUtils.hasLength(resourceName);
    //使用默认名
    if (this.isDefaultName) {
        //获取属性名或方法名
        resourceName = this.member.getName();
        //以set开头的方法
        if (this.member instanceof Method && resourceName.startsWith("set") && resourceName.length() > 3) {
            //实际上就是截取方法名,去掉set,然后将首字母转小写
            resourceName = Introspector.decapitalize(resourceName.substring(3));
        }
    }
    /**
     * 正常情况name写的什么名字,这里就返回什么
     */
    else if (embeddedValueResolver != null) {
        resourceName = embeddedValueResolver.resolveStringValue(resourceName);
    }
    // resourceType的默认值为Object.class
    // 此时在@Resource上指定注入类型
    if (Object.class != resourceType) {
        // 检查指定的类型resourceType是否匹配属性或方法参数
        checkResourceType(resourceType);
    }
    else {
        // 没有指定类型,则根据Member获取类型
        resourceType = getResourceType();
    }
    this.name = (resourceName != null ? resourceName : "");
    this.lookupType = resourceType;
    //这个忽略,没用过
    String lookupValue = resource.lookup();
    this.mappedName = (StringUtils.hasLength(lookupValue) ? lookupValue : resource.mappedName());
    //@Lazy注解处理
    Lazy lazy = ae.getAnnotation(Lazy.class);
    this.lazyLookup = (lazy != null && lazy.value());
}

3、checkConfigMembers()方法的作用

  • 这个方法,查询@Autowired @PostConstruct @PreDestroy @Resource注解元数据后都会调用此方法
  • checkConfigMembers()方法的作用之一是考虑可能存在多个注解同时标注在同一个属性上的情况,避免重复处理
  • 通过将已处理的成员标记为外部管理的配置成员,它确保Spring容器在处理依赖注入时不会重复处理同一个属性
  • 简单理解就是去重,然后将需要处理的数据放入Set<InjectedElement> checkedElements集合中,后续统一处理

三、postProcessProperties(属性填充)

  • 在postProcessProperties 方法中完成了Bean 中@Resource注解的属性填充
  • 上一步postProcessMergedBeanDefinition已经筛选出需要注入的属性放入injectionMetadataCache中
public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
    //获取@Resource注解的注入元数据,前面已经讲过了
    InjectionMetadata metadata = findResourceMetadata(beanName, bean.getClass(), pvs);
    try {
        //执行注入
        metadata.inject(bean, beanName, pvs);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Injection of resource dependencies failed", ex);
    }
    return pvs;
}

1、inject 执行注入

  • 从checkedElements中拿到所有的属性和方法元数据遍历注入
public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
    Collection<InjectedElement> checkedElements = this.checkedElements;
    Collection<InjectedElement> elementsToIterate =
        (checkedElements != null ? checkedElements : this.injectedElements);
    if (!elementsToIterate.isEmpty()) {
        //遍历获取每个需要被注入的元素(属性或方法)
        for (InjectedElement element : elementsToIterate) {
            //无论是属性或方法都封装为ResourceElement
            element.inject(target, beanName, pvs);
        }
    }
}
  • 设置字段和方法的访问性,强行赋值
    • field.setAccessible(true);
    • method.setAccessible(true);
  • getResourceToInject():获取注入的值
protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
    throws Throwable {

	/*********************************属性******************************/    
    if (this.isField) {
        Field field = (Field) this.member;
        //不需要set方法,直接强行赋值
        ReflectionUtils.makeAccessible(field);
        //getResourceToInject(target, requestingBeanName)重点是这个方法
        field.set(target, getResourceToInject(target, requestingBeanName));
    }
	/*********************************方法******************************/        
    else {
        if (checkPropertySkipping(pvs)) {
            return;
        }
        try {
            Method method = (Method) this.member;
            //不管方法的修饰符,强行执行方法
            ReflectionUtils.makeAccessible(method);
            method.invoke(target, getResourceToInject(target, requestingBeanName));
        }
        catch (InvocationTargetException ex) {
            throw ex.getTargetException();
        }
    }
}

2、getResourceToInject() 获取注入的值

  • 懒加载注入,创建一个代理对象返回
  • 一般注入,从spring容器中获取beanName对应的bean对象
protected Object getResourceToInject(Object target, @Nullable String requestingBeanName) {
    /**
	 * (1)懒加载自动注入,创建一个代理对象返回
	 * (2)否则直接去spring容器中获取requestingBeanName对应的bean对象
 	 */
    return (this.lazyLookup ? buildLazyResourceProxy(this, requestingBeanName) :
            getResource(this, requestingBeanName));
}

懒加载注入对象

protected Object buildLazyResourceProxy(final LookupElement element, final @Nullable String requestingBeanName) {
    //创建一个目标资源
    TargetSource ts = new TargetSource() {
        @Override
        public Class<?> getTargetClass() {
            return element.lookupType;
        }
        @Override
        public boolean isStatic() {
            return false;
        }
        @Override
        public Object getTarget() {
            //代理类的目标对象也是getResource方法获取的
            return getResource(element, requestingBeanName);
        }
        @Override
        public void releaseTarget(Object target) {
        }
    };
    //代理工厂
    ProxyFactory pf = new ProxyFactory();
    pf.setTargetSource(ts);
    //设置接口
    if (element.lookupType.isInterface()) {
        pf.addInterface(element.lookupType);
    }
    //类加载器
    ClassLoader classLoader = (this.beanFactory instanceof ConfigurableBeanFactory ?
                               ((ConfigurableBeanFactory) this.beanFactory).getBeanClassLoader() : null);
    //获取代理对象
    return pf.getProxy(classLoader);
}

普通方式注入对象

protected Object getResource(LookupElement element, @Nullable String requestingBeanName)
    throws NoSuchBeanDefinitionException {

    if (StringUtils.hasLength(element.mappedName)) {
        return this.jndiFactory.getBean(element.mappedName, element.lookupType);
    }
    if (this.alwaysUseJndiLookup) {
        return this.jndiFactory.getBean(element.name, element.lookupType);
    }
    //上面两个不用管,jndi相关,没用过
    if (this.resourceFactory == null) {
        throw new NoSuchBeanDefinitionException(element.lookupType,
                                                "No resource factory configured - specify the 'resourceFactory' property");
    }
    //获取匹配的依赖对象
    return autowireResource(this.resourceFactory, element, requestingBeanName);
}
  • 没有指定@Resource注解中的name属性
    • 从容器中根据默认名获取对应bean
    • 根据默认名找不到,通过类型查找注入,还找不到报错
  • 指定@Resource注解中的name属性
    • 从容器中根据指定名称获取bean,找不到报错
protected Object autowireResource(BeanFactory factory, LookupElement element, @Nullable String requestingBeanName)
    throws NoSuchBeanDefinitionException {

    Object resource;
    Set<String> autowiredBeanNames;
    String name = element.name;

    if (factory instanceof AutowireCapableBeanFactory) {
        AutowireCapableBeanFactory beanFactory = (AutowireCapableBeanFactory) factory;
        /**
         * 获取依赖描述
         * 实际上就是
         * new LookupDependencyDescriptor((Field) this.member, this.lookupType);
         * new LookupDependencyDescriptor((Method) this.member, this.lookupType);
         */
        DependencyDescriptor descriptor = element.getDependencyDescriptor();
        /**
         * 默认名字,没有指定name
         * !factory.containsBean(name)成立,容器中没有默认名对应的bean
         */
        if (this.fallbackToDefaultTypeMatch && element.isDefaultName && !factory.containsBean(name)) {
            autowiredBeanNames = new LinkedHashSet<>();
            //使用beanFactory解析依赖描述,获取依赖bean对象
            //该方法上篇文章已经讲过,此处不再赘述,这个方法是核心重点方法,一定要看懂
            resource = beanFactory.resolveDependency(descriptor, requestingBeanName, autowiredBeanNames, null);
            if (resource == null) {
                throw new NoSuchBeanDefinitionException(element.getLookupType(), "No resolvable resource object");
            }
        }
        //按指定名name获取依赖对象
        else {
            //本质上就是factory.getBean(name, element.lookupType);
            resource = beanFactory.resolveBeanByName(name, descriptor);
            autowiredBeanNames = Collections.singleton(name);
        }
    }
    else {
        resource = factory.getBean(name, element.lookupType);
        autowiredBeanNames = Collections.singleton(name);
    }

    //注册依赖关系
    if (factory instanceof ConfigurableBeanFactory) {
        ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory) factory;
        for (String autowiredBeanName : autowiredBeanNames) {
            if (requestingBeanName != null && beanFactory.containsBean(autowiredBeanName)) {
                beanFactory.registerDependentBean(autowiredBeanName, requestingBeanName);
            }
        }
    }
    return resource;
}

四、postProcessBeforeInitialization(执行初始化方法)

  • 执行时机:初始化前其他init初始化方法前执行
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
    //获取所有生命周期元数据
    LifecycleMetadata metadata = findLifecycleMetadata(bean.getClass());
    try {
        //执行生命周期初始化方法
        metadata.invokeInitMethods(bean, beanName);
    }
    catch (InvocationTargetException ex) {
        throw new BeanCreationException(beanName, "Invocation of init method failed", ex.getTargetException());
    }
    catch (Throwable ex) {
        throw new BeanCreationException(beanName, "Failed to invoke init method", ex);
    }
    return bean;
}

执行初始化方法

public void invokeInitMethods(Object target, String beanName) throws Throwable {
    Collection<LifecycleElement> checkedInitMethods = this.checkedInitMethods;
    Collection<LifecycleElement> initMethodsToIterate =
        (checkedInitMethods != null ? checkedInitMethods : this.initMethods);
    if (!initMethodsToIterate.isEmpty()) {
        for (LifecycleElement element : initMethodsToIterate) {
            if (logger.isTraceEnabled()) {
                logger.trace("Invoking init method on bean '" + beanName + "': " + element.getMethod());
            }
            //执行LifecycleElement的invoke方法
            element.invoke(target);
        }
    }
}
public void invoke(Object target) throws Throwable {
    //反射执行生命周期初始化方法
    ReflectionUtils.makeAccessible(this.method);
    this.method.invoke(target, (Object[]) null);
}

五、postProcessBeforeDestruction(执行销毁方法)

  • 执行流程与初始化方法一样,就不说了
  • 执行时机:bean容器关闭 context.close();调用

Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor,spring,spring,java,后端文章来源地址https://www.toymoban.com/news/detail-645574.html

到了这里,关于Spring源码解析(八):bean后置处理器CommonAnnotationBeanPostProcessor的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • (Bean工厂的后处理器入门)学习Spring的第七天

    (Bean工厂的后处理器入门)学习Spring的第七天

    一 . Bean工厂的后处理器入门 : 直接上图 BeanDefinitionRegistyPostProcessor 为 BeanFactoryProcessor的子接口 , 前者先执行(图里只有Bean工厂的后处理器第一个类型) 如下图 : 这两个接口可改变两个Map(BeanDefinitionMap , singletonObject)里的信息 (黑马只讲了BeanFactoryPostProcessor , 第二个应该不重要)

    2024年01月23日
    浏览(9)
  • Jmeter后置处理器——JSON提取器

    Jmeter后置处理器——JSON提取器

    目录 1、简介  2、使用步骤         1)添加线程组         2)添加http请求         3) 添加JSON提取器 1、简介         JSON是一种简单的数据交换格式,允许互联网应用程序快速传输数据。JSON提取器可以从JSON格式响应数据中提取数据、简化从JSON原始数据中提取特

    2024年01月16日
    浏览(7)
  • 【JMeter】后置处理器的分类以及场景介绍

    【JMeter】后置处理器的分类以及场景介绍

    1.常用后置处理器的分类 Json提取器 针对响应体的返回结果是 json格式 的 会自动生成新的变量名为【提取器中 变量名_MatchNr 】,取到的个数由jsonpath expression取到的个数决定 可以当作普通变量调用,调用语法:${ 提取器中 变量名_MatchNr } 正则表达式提取器 返回结果是 任何数

    2024年02月05日
    浏览(9)
  • jmeter-BeanShell预处理器与BeanShell后置处理器的使用

    jmeter-BeanShell预处理器与BeanShell后置处理器的使用

    BeanShell是一个小型嵌入式Java源代码解释器,具有对象脚本语言特性,能够动态地执行标准JAVA语法,并利用在JavaScript和Perl中常见的松散类型、命令、闭包等通用脚本来对其进行拓展。 前置处理器:请求发送之前对请求参数做一些处理 后置处理器:请求发送完成之后对响应数

    2023年04月17日
    浏览(8)
  • 【Jmeter】Request1输出作为Request2输入-后置处理器

    【Jmeter】Request1输出作为Request2输入-后置处理器

    【Jmeter】基础介绍-详细 接上文,继续介绍Jmeter,本文关注点为如何解决上文中提到的第一个问题,即: 需要实现Request1的返回作为Request2的RequestBody或Header Jmeter支持后置处理器,即对http请求(或其他取样器)的返回值进行提取并赋值给变量。 本例中从Request1的ResponseBody中提

    2023年04月20日
    浏览(8)
  • Spring MVC异常处理【单个控制异常处理器、全局异常处理器、自定义异常处理器】

    Spring MVC异常处理【单个控制异常处理器、全局异常处理器、自定义异常处理器】

    目录 一、单个控制器异常处理 1.1 控制器方法 1.2 编写出错页面 1.3 测试结果 二、全局异常处理 2.1 一个有异常的控制器类 2.2 全局异常处理器类 2.3 测试结果  三、自定义异常处理器 3.1 自定义异常处理器 3.2 测试结果 往期专栏文章相关导读  1. Maven系列专栏文章 2. Mybatis系列

    2024年02月16日
    浏览(8)
  • Spring异常处理器

    Spring异常处理器

     问题:   程序允许不免的在各层都可能会产生异常,我们该如何处理这些异常? 如果只是在方法里面单独使用 try… catch… 语句去一个一个的进行捕捉处理的话,那毫无疑问是不现实的,因为异常数量是非常庞大的并且对于异常的出现种类是不可预料的,于是我们可以使用

    2024年02月13日
    浏览(10)
  • Spring MVC 异常处理器

    Spring MVC 异常处理器

    如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。 系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图: 编写controller 在index.jsp里面定义超链接

    2024年01月22日
    浏览(12)
  • spring框架_常见工厂后处理器

    spring框架_常见工厂后处理器

    ConfigurationClassPostProcessor :用于解析@ComponentScan @Bean @Import @ImportResource MapperSacnnerConfigurer :相当于Mybatis的@MapperScanner 用于解析被标注的@Mapper接口 @mapper 注解的解析:@mapper注解是mybatis提供的,用于标明一个接口,spring自然无法管理接口,要将这个接口转化为一个bean加入到beanfa

    2024年02月05日
    浏览(43)
  • Spring MVC配置全局异常处理器!!!

    Spring MVC配置全局异常处理器!!!

    为什么要使用全局异常处理器:如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。 系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图: 结果展示:  

    2024年01月15日
    浏览(6)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包