Spring源码-applyMergedBeanDefinitionPostProcessors方法处理@PreDestroy、@PostConstruct @Resource

调用起始位置

AbstractAutowireCapableBeanFactory#doCreateBean方法调用当前类下applyMergedBeanDefinitionPostProcessors方法
在这里插入图片描述
在这里插入图片描述

CommonAnnotationBeanPostProcessor类

在这里插入图片描述

添加PostConstruct和PreDestroy
在这里插入图片描述
实际是InitDestroyAnnotationBeanPostProcessor的方法


	/**
	 * Specify the init annotation to check for, indicating initialization
	 * methods to call after configuration of a bean.
	 * <p>Any custom annotation can be used, since there are no required
	 * annotation attributes. There is no default, although a typical choice
	 * is the JSR-250 {@link javax.annotation.PostConstruct} annotation.
	 */
	public void setInitAnnotationType(Class<? extends Annotation> initAnnotationType) {
   
   
		this.initAnnotationType = initAnnotationType;
	}

	/**
	 * Specify the destroy annotation to check for, indicating destruction
	 * methods to call when the context is shutting down.
	 * <p>Any custom annotation can be used, since there are no required
	 * annotation attributes. There is no default, although a typical choice
	 * is the JSR-250 {@link javax.annotation.PreDestroy} annotation.
	 */
	public void setDestroyAnnotationType(Class<? extends Annotation> destroyAnnotationType) {
   
   
		this.destroyAnnotationType = destroyAnnotationType;
	}

添加Resource
在这里插入图片描述
static方法赋值的属性字段在common类里

	private static final Set<Class<? extends Annotation>> resourceAnnotationTypes = new LinkedHashSet<>(4);

调用CommonAnnotationBeanPostProcessor的postProcessMergedBeanDefinition

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

/**
	 * 构造生命周期元数据(解析带@PostConstruct和@PreDestroy注解的方法),当其构造完成后会将元数据缓存到lifecycleMetadataCache集合中并返回
	 * 此时就完成了相关方法(初始化方法和销毁方法)的扫描解析和缓存工作
	 *
	 * @param clazz
	 * @return
	 */
	private LifecycleMetadata buildLifecycleMetadata(final Class<?> clazz) {
   
   
		if (!AnnotationUtils.isCandidateClass(clazz, Arrays.asList(this.initAnnotationType, this.destroyAnnotationType))) {
   
   
			return this.emptyLifecycleMetadata;
		}

		// 实例化后的回调方法(@PostConstruct)
		List<LifecycleElement> initMethods = new ArrayList<>();
		// 销毁前的回调方法(@PreDestroy)
		List<LifecycleElement> destroyMethods = new ArrayList<>();
		// 获取正在处理的目标类
		Class<?> targetClass = clazz;

		do {
   
   
			// 保存每一轮循环搜索到的相关方法
			final List<LifecycleElement> currInitMethods = new ArrayList<>();
			final List<LifecycleElement> currDestroyMethods = new ArrayList<>();
			// 反射获取当前类中的所有方法并依次对其调用第二个参数的lambda表达式
			ReflectionUtils.doWithLocalMethods(targetClass, method -> {
   
   
				// 当前方法的注解中包含initAnnotationType注解时(@PostConstruct)
				if (this.initAnnotationType != 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值