Spring IOC:ConfigurationClassPostProcessor解析(2)postProcessBeanFactory使用CGLIB增强配置类

spring核心源码分析第五篇 refresh流程之postProcessBeanFactory postProcessBeanFactory作用 AbstractApplicationContext并没有任何实现,但其允许在上下文子类中重写 其方法的注释翻译如下: 在beanfactory加载完毕后,尚未构建BeanDefinition和实例化之前,允许子类覆写ApplicationContext来实现相关功能,例如: 修改BeanFactory 或者注册BeanPostProcessor等等 spring并没有约束子类重写后具体的实现,只是告知当前的被执行时机是beanFactory加载完成,Be 阅读详情

引言

在Spring IOC:ConfigurationClassPostProcessor解析提到对于配置类,不管是否使用了@Configuration都会进行注解的解析,那么@Configuration到底还有什么其他的作用呢?
Appconfig配置类

@Configuration
@ComponentScan("com.st")
public class Appconfig {
	@Bean
	public UserDao getUserDao(){
		return new UserDao();
	}

	@Bean
	public UserDao2 getUserDao2(){
		getUserDao();
		return new UserDao2();
	}
}

新建UserDao对象

package com.st.dao;

public class UserDao {
	public UserDao() {
		System.out.println("userDao1--init");
	}

	public void query(){}
}

新建UserDao2对象

package com.st.dao;

public class UserDao2 {
	public UserDao2() {
		System.out.println("UserDao2--init");
	}
	public void query(){}
}

package com.st.test;

import com.st.config.Appconfig;
import com.st.config.MyBeanFactoryPostProcessor;
import com.st.dao.Indexdao;
import com.st.dao.Indexdao2;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Test {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.register(Appconfig.class);
		//context.refresh();
		//context.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
		context.refresh();
		//Indexdao2 indexdao = context.getBean(Indexdao2.class);
		//System.out.println(indexdao.getClass().getName());
	//	System.out.println(indexdao.hashCode()+"-------"+indexdao1.hashCode());
	}
}

当我们在配置类中使用了@Bean注解,在getUserDao2()中调用了getUserDao()
可以看到getUserDao()中创建了一个UserDao对象,而调用new UserDao()必然会执行对应的构造方法,所以在这里UserDao的无参构造会输出几次init呢?
执行结果:
在这里插入图片描述
说明了getUserDao()返回的是已经创建好的单例对象
现在把@Configuration去掉
执行结果:
在这里插入图片描述

@Configuration进行Cglib增强

在上一章节讲到了ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法,spring执行完这个方法之后还会执行这个类的postProcessBeanFactory方法。就是在这里对@Configuration进行了Cglib增强,使得getUser()时返回的是已产生的单例对象

@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {

		int factoryId = System.identityHashCode(beanFactory);
		if (this.factoriesPostProcessed.contains(factoryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + beanFactory);
		}
		this.factoriesPostProcessed.add(factoryId);
		// postProcessorBeanFactory()方法也会调用processConfigBeanDefinitions方法,为了避免重复执行,
		// 所以在执行方法之前会先生成一个id,将id放入到一个set当中,每次执行之前
		// 先判断id是否存在,所以在此处,不会进入到if语句中
		if (!this.registriesPostProcessed.contains(factoryId)) {
			// BeanDefinitionRegistryPostProcessor hook apparently not supported...
			// Simply call processConfigurationClasses lazily at this point then.
			processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
		}
		//对@Configuration进行Cglib增强
		enhanceConfigurationClasses(beanFactory);
		beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
	}

进入enhanceConfigurationClasses(beanFactory)正式对@Configuration进行Cglib增强

public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
		Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
		for (String beanName : beanFactory.getBeanDefinitionNames()) {
			BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
			//拿到全注解的配置类
			//return CONFIGURATION_CLASS_FULL.equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE));
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
				//省略。。。
			}
		}
		if (configBeanDefs.isEmpty()) {
			// nothing to enhance -> return immediately
			return;
		}

		ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
		for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
			AbstractBeanDefinition beanDef = entry.getValue();
			// If a @Configuration class gets proxied, always proxy the target class
			beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
			try {
				// Set enhanced subclass of the user-specified bean class
				Class<?> configClass = beanDef.resolveBeanClass(this.beanClassLoader);
				if (configClass != null) {
				   //调用ConfigurationClassEnhancer.enhance()方法创建增强类
					Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
					if (configClass != enhancedClass) {
						if (logger.isDebugEnabled()) {
							logger.debug(String.format("Replacing bean definition '%s' existing class '%s' with " +
									"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
						}
						beanDef.setBeanClass(enhancedClass);
					}
				}
			}
			catch (Throwable ex) {
				throw new IllegalStateException("Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
			}
		}
	}

调用ConfigurationClassEnhancer.enhance()方法创建增强类,重点关注newEnhancer(configClass, classLoader)

public Class<?> enhance(Class<?> configClass, @Nullable ClassLoader classLoader) {
		if (EnhancedConfiguration.class.isAssignableFrom(configClass)) {
			//省略。。。
		}
		//重点关注newEnhancer(configClass, classLoader)
		Class<?> enhancedClass = createClass(newEnhancer(configClass, classLoader));
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("Successfully enhanced %s; enhanced class name is: %s",
					configClass.getName(), enhancedClass.getName()));
		}
		return enhancedClass;
	}

为appconfig创建cglib,这里的重点是为cglib对象加入了父类,因为cglib是基于继承实现的。还有就是加入了两个拦截器BeanMethodInterceptor,BeanFactoryAwareMethodInterceptor,实现了config类的增强

/**
	 * Creates a new CGLIB {@link Enhancer} instance.
	 */
	private Enhancer newEnhancer(Class<?> configSuperClass, @Nullable ClassLoader classLoader) {
		Enhancer enhancer = new Enhancer();
		//增强父类,Cglib的代理是基于父类的
		enhancer.setSuperclass(configSuperClass);
		//增强接口,为什么要增强接口?便于判断,表示一个类被增强了
		//基于接口的EnhancedConfiguration的父接口BeanFactoryAware中的setBeanFactory方法
		//设置这个变量的值为当前Context中的beanFactory,这个cglib代理类就有了beanFactory,这样就可以通过beanFactory获取对象了
		enhancer.setInterfaces(new Class<?>[] {EnhancedConfiguration.class});
		enhancer.setUseFactory(false);
		enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
		/*BeanFactoryAwareGeneratorStrategy是一个生成策略
		主要是为了生成的Cglib类中设置属性添加成员变量$$beanFactory
		BeanFactoryAwareGeneratorStrategy#transform	declare_field(Constants.ACC_PUBLIC, BEAN_FACTORY_FIELD, Type.getType(BeanFactory.class), null);
		*/
		enhancer.setStrategy(new BeanFactoryAwareGeneratorStrategy(classLoader));
		//当前的CALLBACK_FILTER为ConditionalCallbackFilter CALLBACK_FILTER = new ConditionalCallbackFilter(CALLBACKS);
		//CALLBACKS 为 new Callback[] {
		//			new BeanMethodInterceptor(),//调用intercept方法实现拦截,对加了@Bean注解的方法进行增强
		//			new BeanFactoryAwareMethodInterceptor(),//调用intercept方法实现拦截,为代理对象的beanFactory属性进行增强
		//			NoOp.INSTANCE }
		enhancer.setCallbackFilter(CALLBACK_FILTER);
		enhancer.setCallbackTypes(CALLBACK_FILTER.getCallbackTypes());
		return enhancer;
	}

BeanMethodInterceptor#intercept方法

public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
					MethodProxy cglibMethodProxy) throws Throwable {
			//通过enhancedConfigInstance中cglib的成员遍历$$beanFactory获得beanFactory
			ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
			String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);

			// Determine whether this bean is a scoped-proxy
			Scope scope = AnnotatedElementUtils.findMergedAnnotation(beanMethod, Scope.class);
			if (scope != null && scope.proxyMode() != ScopedProxyMode.NO) {
				String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
				if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
					beanName = scopedBeanName;
				}
			}

			
			//首先检查当前bean是不是一个FactoryBean,如果是就创建一个代理子类调用getObject方法返回一个bean实例
			if (factoryContainsBean(beanFactory, BeanFactory.FACTORY_BEAN_PREFIX + beanName) &&
					factoryContainsBean(beanFactory, beanName)) {
				Object factoryBean = beanFactory.getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
				if (factoryBean instanceof ScopedProxyFactoryBean) {
					// Scoped proxy factory beans are a special case and should not be further proxied
				}
				else {
					// It is a candidate FactoryBean - go ahead with enhancement
					return enhanceFactoryBean(factoryBean, beanMethod.getReturnType(), beanFactory, beanName);
				}
			}
			//判断执行的方法和调用的方法是不是同一个方法
			//当执行到@Bean方法内调用其他getUserObject方法这里的执行方法和调用方法就不是同一个了
			if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
				// The factory is calling the bean method in order to instantiate and register the bean
				// (i.e. via a getBean() call) -> invoke the super implementation of the method to actually
				// create the bean instance.
				if (logger.isWarnEnabled() &&
						BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
					
				}
				//创建bean并返回
				return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
			}
			//返回已经创建好的bean实例
			return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
		}

BeanFactoryAwareMethodInterceptor#intercept 为代理对象设置beanFactory属性

public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
			Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD);
			Assert.state(field != null, "Unable to find generated BeanFactory field");
			field.set(obj, args[0]);

			// Does the actual (non-CGLIB) superclass implement BeanFactoryAware?
			// If so, call its setBeanFactory() method. If not, just exit.
			if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) {
				return proxy.invokeSuper(obj, args);
			}
			return null;
		}
第17篇:深入解析OpenEuler 24.03系统中的逻辑卷管理(LVM) OpenEuler 24.03系统中的逻辑卷管理(LVM)提供了灵活的存储管理方案,通过在物理存储与文件系统间构建抽象层实现动态资源分配。 阅读详情

相关推荐

捷联惯导总结--初始对准,位置标定,INS姿态更新,GPS/INS组合

惯导及组合导航回顾  2018.09.16 今天和17系的同学一起把惯导的流程捋了一遍,为了加深自己的记忆,这里在前面把心得大致列出来。 我们这里只考虑捷联式惯导及松组合 首先拿到惯性传感器(加速度计和陀螺仪)需要对其进行标定,是为了求出零偏,比例因子,交轴耦合这些误差。这些误差有的虽然在出厂时会给出,但是考虑到实际环境不同,还是要做标定。一般采用的是六位置旋转法,针对加速度计和陀螺仪同时...

赤豆几维 5万+

ConfigurationClassPostProcessor详解

预先了解一下ConfigurationClassPostProcessor是怎么来的:在context的refresh阶段中调用invokeBeanFactoryPostProcessors函数时首先执行接口BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry,在执行其父接口BeanFactoryPostProcessor中的postProcessBeanFactory方法。

zhou_jianwei的博客 242

告别硬件!用Wokwi在线模拟ESP32点灯,5分钟搞定开发环境搭建

本文介绍如何使用Wokwi在线模拟器快速搭建ESP32开发环境,5分钟内完成点灯实验。无需硬件即可体验GPIO控制、PWM调光等核心功能,特别适合物联网开发初学者和快速原型验证。Wokwi的零成本、全功能模拟特性让嵌入式开发变得前所未有的简单高效。

weixin_42567497的博客 504

Spring——关于postProcessBeanFactory(beanFactory)的思考

文章目录1. postProcessBeanFactory(beanFactory)的思考2. 自定义实现ApplicationContext对象,重写postProcessBeanFactory(beanFactory)方法。3. 思考的结果 1. postProcessBeanFactory(beanFactory)的思考 此方法是在refresh()模板方法中,但是此方法的实现是空的。因为此方法的参数是BeanFactory,所以我们可以重写此方法,然后针对beanFactory进行一些修改。 2.

zl13101758272的博客 2405

MOEAD算法

这个算法的精髓在于通过聚合函数把多目标优化问题转化为单目标优化。首先需要在目标空间均匀分布权重,以下面图为例,权重的数量与种群规模相同,种群规模是N,那么权重的数量就是N。每组权重向量将多目标优化问题转化为一个单目标优化问题。N组权重向量就是N个单目标优化问题。 下面我们说说,怎么分解的。加权法我们就不说了,解决不了非凸函数。切比雪夫和边界交叉相比,切比雪夫用的比较多,我们就以切比雪夫为例解...

Panpan Wei的博客 1万+

AI安全护栏评测:TrustedExecBench如何量化评估大模型防护能力

在人工智能和机器学习领域,模型安全对齐是确保AI系统可靠、可控的核心技术。其原理是通过设计安全机制(即“护栏”)来约束模型行为,防止生成有害、偏见或越界内容。这项技术的核心价值在于平衡AI能力与风险管控,是可信AI部署的基石。应用场景广泛覆盖内容审核、对话系统、代码生成等需要人机交互的领域。本文聚焦的TrustedExecBench项目,正是针对“护栏”性能量化评估这一痛点,提供了一个标准化、自动化的开源评测框架。该工具通过构建多维度的恶意测试套件,并引入基于模型的动态评判机制,能够系统性地检验大语言模型在

weixin_42525428的博客 383

springBoot1.5.9.RELEASE启动源码分析之ConfigurationClassPostProcessor#postProcessBeanFactory

1.上篇文章讲到了ConfigurationClassPostProcessor中的postProcessBeanDefinitionRegist,接下来讲postProcessBeanFactory方法,主要的方法入口关系run->refreshContext->invokeBeanFactoryPostProcessors->postProcessBeanFactory; ...

weixin_42739473的博客 407

在 ABAP SEGW OData 服务里,把 Function Import 参数长度校验真正跑起来

SAP Gateway服务中Function Import参数长度校验的实现机制解析:在SEGW中定义Max Length参数后,需通过模型特性USE_STRICT_FUNCTION_PARAM_CHK(7.52+版本支持)启用严格检查。该特性需在MPC_EXT的DEFINE方法中设置,框架会在URI解析阶段拦截超长参数,避免错误进入业务逻辑。对于低版本系统,建议在应用层手动添加校验。这种模型驱动的方式符合Clean Core原则,能有效提升接口健壮性。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 508

BeanFactoryPostProcessor的调用时机

BeanFactoryPostProcessor的调用时机 BeanFactoryPostProcessor其实就是BeanFactory(创建bean的工厂)的后置处理器。说起这个,你脑海中是不是泛起了回忆,是不是想起了有一个与BeanFactoryPostProcessor的名字极其相似的玩意,它就是BeanPostProcessor。那什么是BeanPostProcessor呢?我们之前早就说过了,它就是bean的后置处理器,并且是在bean创建对象初始化前后进行拦截工作的。 现在我们要讲解的是Bea

weixin_45723046的博客 2111

Yolov8-pose关键点检测:通用倒瓶颈(UIB)搜索块结合C2f二次创新 | 轻量化之王MobileNetV4

通用倒瓶颈(UIB)搜索块结合C2f二次创新

①答疑群聊服务;②YOLO大模型知识问答系统;③计算机视觉论文生成智能体; 619

LVGL hal disp(porting display)

LVGL本身是没有对接最终的显示框架的,所以到具体的某个平台上,需要自行porting。

Bigan(安)的博客 2099

BeanFactory和PostProcessor详解

BeanFactory详解

weixin_56690415的博客 2651

【零基础学习CAPL】——CAN报文的发送(CRC——ChecSum值)

本章主要介绍带有CRC值的报文发送一般报文可使用CANoe的IG模块直接发送,但带有CRC值的报文就只能编写脚本进行发送,以下详细讲解在配合Panel面板情况下,如何进行带有循环冗余码的报文进行报文的发送。

LOVE135149的博客 1922

SpringBoot配置类解析-ConfigurationClassPostProcessor后置处理器

ConfigurationClassPostProcessor是一个BeanFactory的后置处理器,因此它的主要功能是参与BeanFactory的建造,在这个类中,会解析加了@Configuration的配置类,还会解析@ComponentScan、@ComponentScans注解扫描的包,以及解析@Import等注解。 ConfigurationClassPostProcessor主要重写了BeanDefinitionRegistryPostProcessor的postProcessBeanDe

BushRo 2780

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

03 Spring 源码总结 - ConfigurationClassPostProcessor

03 Spring 源码总结 - ConfigurationClassPostProcessor

刘元雄 192

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Spring干货---IOC

spring ioc介绍,只讲干货,不说废话

zhzhxian的博客 422

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

专项攻克——spring、springMVC、springBoot、springCloud的启动流程

参考文献:https://blog.csdn.net/m0_47495420/article/details/114422268?

军威兄的博客 234

Java八股文学习记录

个人java学习

apple_74621612的博客 414

BeanFactoryPostProcessor

BeanFactory是Spring中容器功能的基础,用于存放所有已经加载的bean,为了保证程序上的高可扩展性,Spring针对BeanFactory做了大量的扩展. 激活注册BeanFactoryPostProcessor BeanFactoryPostProcessor和BeanPostProcessor类似,可以对beanDefinition进行处理,也就是说SpringIOC容器允许BeanFactoryPostProcessor在容器实际实例化任何bean之前读取beanDefinition,并

qq_40708942的博客 1万+

Spring源码系列(四)——ConfigurationClassPostProcessor功能解析

Spring源码系列(四)——ConfigurationClassPostProcessor功能解析

scorpio的博客 1098

五、Spring源码学习之postProcessBeanFactory方法

Spring源码学习之postProcessBeanFactory方法

weixin_44877172的博客 580

Spring经典扩展接口应用:BeanFactoryPostProcessor

对BeanFactoryPostProcessor基本知识总结,并给出框架中的应用举例分析,再次给出扩展应用代码举例和一些建议,最后简单分析对应的源码分析

曾经“等你生日那天”都遥远得像未来,如今却可欢愉的挥手说“下个十年见” 6万+

Spring源码学习笔记(五)、postProcessBeanFactory

/ 允许在上下文子类中对bean工厂进行后处理, 相当于beanFactory的后置处理器Spring中并没有具体去实现postProcessBeanFactory方法,相当于定义了一个模板方法,提供给想要实现BeanPostProcessor的三方框架使用的。谁要使用谁就去实现。作用是在BeanFactory准备工作完成后做一些定制化的处理,一般结合BeanPostProcessor接口的实现类一起使用,注入一些重要资源(类似Application的属性和ServletContext的属性)。

dongdong199033的博客 545

BeanFactoryPostProcessor深度解读

文章目录一、前言二、BeanFactoryPostProcessor介绍三、相关类介绍1、ConfigurationClassPostProcessor2、自定义后置处理器四、执行流程1、调用链及其他措施2、核心方法的执行①、相关变量介绍②、执行参数的postProcessBeanDefinitionRegistry()③、实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor④、实现了Ordered接口的BeanDefinitionRegistry

qq_43581718的博客 8965

5-spring源码阅读之postProcessBeanFactory方法

上一节已经说过了prepareBeanFactory方法,这一节来看看这个方法。这个方法是spring团队给框架扩展的留的一个点,单独的spring源码中是没有使用到的,因为这是一个空方法,并没有做什么处理,只有在spring MVC 和spring boot里面才对该方法做了重写。

酸萝卜别吃 2200

一文吃透Spring Boot扩展之BeanFactoryPostProcessor

是Spring中一个相当重要的扩展点,扩展点就是能让我们在Spring容器以及Bean生命周期的各个阶段中可以进行修改扩展。, 翻译过来大致是Bean的工厂处理器,顾名思义,可以理解为它对Bean工厂中Bean定义()进行修改, 它的执行时机:BeanFactory标准初始化之后,所有的Bean定义已经被加载,但标准Bean的实例还没被创建(不包括类型)。该方法通常用于修改bean的定义,Bean的属性值等,甚至可以在此快速初始化Bean。而另外一个相关的扩展接口的,继承自,所有的Bean定义即将被加载,但

yangjnsjbad的博客 944
上一篇: Spring IOC:ConfigurationClassPostProcessor解析
下一篇: JVM:垃圾回收器和内存分配策略
大大君
博客等级 码龄10年 3粉丝 9原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值