前面有一篇说了spring的解析xml,解析xml最终的作用就是生成BeanDefinition。而实例化的时候会先得到BeanDefinition,而这BeanDefinition已经包含了实例化所有的属性,包括class,property等。详细见前面文章。
解析xml的时候是没有初始化的,而是在第一次getBean的时候才会实例化,当然也可以通过lazy-init这个属性来控制。也就是启动的时候是否加载。一般的情况下是会加载,虽然比较慢。但是比到使用的时候再加载更加的快。因为有些业务需要很快处理完成,而你加载又浪费掉一段时间。所以一般情况下是启动就加载了。无论是否lazy-init,实例化调用的都是AbstractBeanFactory类的getBean(String beanName)方法。spring实例化的时候不仅仅是简单的new一个bean,其实有很多的工作。图片如下:
这里我只是详细的讲解第一步和第二部。后面的几步就放到后面去讲,AOP的实现实际是和BeanPostProcessor有很大的关系。其实AOP的实现就是用BeanPostProcessor来实现的。实例化和设置属性的调用图如下:
AbstractBeanFactory.getBean --> AbstractBeanFactory.doGetBean --> AbstractBeanFactory.getMergedLocalBeanDefinition --> DefaultListableBeanFactory.getBeanDefinition --> AbstractAutowireCapableBeanFactory.createBean --> AbstractAutowireCapableBeanFactory.doCreateBean --> AbstractAutowireCapableBeanFactory.createBeanInstance -->AbstractAutowireCapableBeanFactory.populateBean
其中实例化是调用到SimpleInstantiationStrategy类的
public Object instantiate(RootBeanDefinition beanDefinition, String beanName, BeanFactory owner) { // Don't override the class with CGLIB if no overrides. if (beanDefinition.getMethodOverrides().isEmpty()) { Constructor<?> constructorToUse; synchronized (beanDefinition.constructorArgumentLock) { constructorToUse = (Constructor<?>) beanDefinition.resolvedConstructorOrFactoryMethod; if (constructorToUse == null) { final Class clazz = beanDefinition.getBeanClass(); if (clazz.isInterface()) { throw new BeanInstantiationException(clazz, "Specified class is an interface"); } try { if (System.getSecurityManager() != null) { constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor>() { public Constructor run() throws Exception { return clazz.getDeclaredConstructor((Class[]) null); } }); } else { constructorToUse = clazz.getDeclaredConstructor((Class[]) null); } beanDefinition.resolvedConstructorOrFactoryMethod = constructorToUse; } catch (Exception ex) { throw new BeanInstantiationException(clazz, "No default constructor found", ex); } } } return BeanUtils.instantiateClass(constructorToUse); } else { // Must generate CGLIB subclass. return instantiateWithMethodInjection(beanDefinition, beanName, owner); } }
上面的实例化有通过JVM的反射和CGLIB两种方式实例化bean,默认是JVM的反射。这里就是通过class得到构造函数然后实例化。而属性的实例化则是会调用到AbstractAutowireCapableBeanFactory的applyPropertyValues方法。而最终会是在BeanWrapperImpl类中一下方法
private void setPropertyValue(PropertyTokenHolder tokens, PropertyValue pv) throws BeansException {
String propertyName = tokens.canonicalName;
String actualName = tokens.actualName;
if (tokens.keys != null) {
// Apply indexes and map keys: fetch value for all keys but the last one.
PropertyTokenHolder getterTokens = new PropertyTokenHolder();
getterTokens.canonicalName = tokens.canonicalName;
getterTokens.actualName = tokens.actualName;
getterTokens.keys = new String[tokens.keys.length - 1];
System.arraycopy(tokens.keys, 0, getterTokens.keys, 0, tokens.keys.length - 1);
Object propValue;
try {
propValue = getPropertyValue(getterTokens);
}
catch (NotReadablePropertyException ex) {
throw new NotWritablePropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "'", ex);
}
// Set value for last key.
String key = tokens.keys[tokens.keys.length - 1];
if (propValue == null) {
throw new NullValueInNestedPathException(getRootClass(), this.nestedPath + propertyName,
"Cannot access indexed value in property referenced " +
"in indexed property path '" + propertyName + "': returned null");
}
else if (propValue.getClass().isArray()) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class requiredType = propValue.getClass().getComponentType();
int arrayIndex = Integer.parseInt(key);
Object oldValue = null;
try {
if (isExtractOldValueForEditor()) {
oldValue = Array.get(propValue, arrayIndex);
}
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
Array.set(propValue, arrayIndex, convertedValue);
}
catch (IndexOutOfBoundsException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Invalid array index in property path '" + propertyName + "'", ex);
}
}
else if (propValue instanceof List) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class requiredType = GenericCollectionTypeResolver.getCollectionReturnType(
pd.getReadMethod(), tokens.keys.length);
List list = (List) propValue;
int index = Integer.parseInt(key);
Object oldValue = null;
if (isExtractOldValueForEditor() && index < list.size()) {
oldValue = list.get(index);
}
Object convertedValue = convertIfNecessary(propertyName, oldValue, pv.getValue(), requiredType,
new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), requiredType));
if (index < list.size()) {
list.set(index, convertedValue);
}
else if (index >= list.size()) {
for (int i = list.size(); i < index; i++) {
try {
list.add(null);
}
catch (NullPointerException ex) {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Cannot set element with index " + index + " in List of size " +
list.size() + ", accessed using property path '" + propertyName +
"': List does not support filling up gaps with null elements");
}
}
list.add(convertedValue);
}
}
else if (propValue instanceof Map) {
PropertyDescriptor pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
Class mapKeyType = GenericCollectionTypeResolver.getMapKeyReturnType(
pd.getReadMethod(), tokens.keys.length);
Class mapValueType = GenericCollectionTypeResolver.getMapValueReturnType(
pd.getReadMethod(), tokens.keys.length);
Map map = (Map) propValue;
// IMPORTANT: Do not pass full property name in here - property editors
// must not kick in for map keys but rather only for map values.
Object convertedMapKey = convertIfNecessary(null, null, key, mapKeyType,
new PropertyTypeDescriptor(pd, new MethodParameter(pd.getReadMethod(), -1), mapKeyType));
Object oldValue = null;
if (isExtractOldValueForEditor()) {
oldValue = map.get(convertedMapKey);
}
// Pass full property name and old value in here, since we want full
// conversion ability for map values.
Object convertedMapValue = convertIfNecessary(
propertyName, oldValue, pv.getValue(), mapValueType,
new TypeDescriptor(new MethodParameter(pd.getReadMethod(), -1, tokens.keys.length + 1)));
map.put(convertedMapKey, convertedMapValue);
}
else {
throw new InvalidPropertyException(getRootClass(), this.nestedPath + propertyName,
"Property referenced in indexed property path '" + propertyName +
"' is neither an array nor a List nor a Map; returned value was [" + pv.getValue() + "]");
}
}
else {
PropertyDescriptor pd = pv.resolvedDescriptor;
if (pd == null || !pd.getWriteMethod().getDeclaringClass().isInstance(this.object)) {
pd = getCachedIntrospectionResults().getPropertyDescriptor(actualName);
if (pd == null || pd.getWriteMethod() == null) {
if (pv.isOptional()) {
logger.debug("Ignoring optional value for property '" + actualName +
"' - property not found on bean class [" + getRootClass().getName() + "]");
return;
}
else {
PropertyMatches matches = PropertyMatches.forProperty(propertyName, getRootClass());
throw new NotWritablePropertyException(
getRootClass(), this.nestedPath + propertyName,
matches.buildErrorMessage(), matches.getPossibleMatches());
}
}
pv.getOriginalPropertyValue().resolvedDescriptor = pd;
}
Object oldValue = null;
try {
Object originalValue = pv.getValue();
Object valueToApply = originalValue;
if (!Boolean.FALSE.equals(pv.conversionNecessary)) {
if (pv.isConverted()) {
valueToApply = pv.getConvertedValue();
}
else {
if (isExtractOldValueForEditor() && pd.getReadMethod() != null) {
final Method readMethod = pd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers()) &&
!readMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
readMethod.setAccessible(true);
return null;
}
});
}
else {
readMethod.setAccessible(true);
}
}
try {
if (System.getSecurityManager() != null) {
oldValue = AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
return readMethod.invoke(object);
}
}, acc);
}
else {
oldValue = readMethod.invoke(object);
}
}
catch (Exception ex) {
if (ex instanceof PrivilegedActionException) {
ex = ((PrivilegedActionException) ex).getException();
}
if (logger.isDebugEnabled()) {
logger.debug("Could not read previous value of property '" +
this.nestedPath + propertyName + "'", ex);
}
}
}
valueToApply = convertForProperty(propertyName, oldValue, originalValue, pd);
}
pv.getOriginalPropertyValue().conversionNecessary = (valueToApply != originalValue);
}
final Method writeMethod = (pd instanceof GenericTypeAwarePropertyDescriptor ?
((GenericTypeAwarePropertyDescriptor) pd).getWriteMethodForActualAccess() :
pd.getWriteMethod());
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers()) && !writeMethod.isAccessible()) {
if (System.getSecurityManager()!= null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
writeMethod.setAccessible(true);
return null;
}
});
}
else {
writeMethod.setAccessible(true);
}
}
final Object value = valueToApply;
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
public Object run() throws Exception {
writeMethod.invoke(object, value);
return null;
}
}, acc);
}
catch (PrivilegedActionException ex) {
throw ex.getException();
}
}
else {
writeMethod.invoke(this.object, value);
}
}
catch (TypeMismatchException ex) {
throw ex;
}
catch (InvocationTargetException ex) {
PropertyChangeEvent propertyChangeEvent =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
if (ex.getTargetException() instanceof ClassCastException) {
throw new TypeMismatchException(propertyChangeEvent, pd.getPropertyType(), ex.getTargetException());
}
else {
throw new MethodInvocationException(propertyChangeEvent, ex.getTargetException());
}
}
catch (Exception ex) {
PropertyChangeEvent pce =
new PropertyChangeEvent(this.rootObject, this.nestedPath + propertyName, oldValue, pv.getValue());
throw new MethodInvocationException(pce, ex);
}
}
}
其中的PropertyTokenHolder是发现如果属性中有配置[],即配置了向一下的
<property name="father.array[0]" value="1" />
<property name="father.array[1]" value="2" />
<property name="map[a]" value="2" />
等就会使用到PropertyTokenHolder,并且里面的keys则不为空。如果没有则是使用到PropertyDescriptor,然后得到javabean的writeMethod方法设置属性。在BeanWrapperImpl是有一个缓存的机制缓存了bean的内省结果,这样就更加的快速得到bean的PropertyDescriptor,从而得到writeMethod。其中的值是直接是通过PropertyValue得到,在解析xml的时候已经完整的设置好了。这里还有一个概念,如果发现bean是关联到了另外的bean,则关联的bean是在本身的bean前被实例化并设置好属性,知道发现没有关联其他的bean。
到这里就算实例化bean和设置属性完成了。这里用到的知识点就是JVM的反射和JavaBean的内省等。而在这里的时候又会发现读取xml的时候为什么不简单的使用map保存属性,而是用PropertyValue来了,这里PropertyValue中的PropertyDescriptor、convertedValue都使用到了。其中的convertedValue在解析时并不是我们使用到的String类型等,像String类型对应的是TypedStringValue,而是到这里才会转换成String类型。并设置PropertyValue的convertedValue的值。
相关推荐
《Spring Framework 4.0源码深度解析》 Spring Framework是Java开发中广泛使用的轻量级框架,它为创建高效、灵活且可测试的应用程序提供了基础。Spring 4.0版本是一个重要的里程碑,引入了许多改进和新特性,使得...
- **Bean的创建与管理**:解析XML或注解配置,通过DefaultListableBeanFactory实现bean的实例化、初始化和依赖注入。 - **AOP实现**:通过ProxyFactoryBean或AspectJ自动代理实现切面编程。 - **Spring MVC的执行...
3. **源码分析**: 深入理解Hessian源码对于优化和定制Hessian服务非常重要。源码可能包含了Hessian序列化和反序列化的实现细节,以及处理异常和错误的方式。通过阅读源码,你可以了解到Hessian如何处理不同类型的...
源码中会包含类定义、对象实例化、继承、多态、封装等基本概念。 2. **MVC架构**:模型-视图-控制器(Model-View-Controller)是一种常见的软件设计模式,常用于Web应用开发。源码中可能包含了分离业务逻辑(Model...
人脸识别项目实战
深度学习教程和开发计划.zip
c语言学习
基本版贪吃蛇源代码.zip
项目资源包含:可运行源码+sql文件+ python3.8+django+mysql5.7+vue 适用人群:学习不同技术领域的小白或进阶学习者;可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 项目具有较高的学习借鉴价值,也可拿来修改、二次开发。 有任何使用上的问题,欢迎随时与博主沟通,博主看到后会第一时间及时解答。 Django==3.2.11 PyMySQL==1.0.2 djangorestframework==3.13.0 django-cors-headers==3.13.0 Pillow==9.1.1 psutil==5.9.4
Abaqus螺栓拧紧过程仿真 (1)螺栓螺母可实现参数化建模,全部采用六面体C3D8R单元建模 (2)施加边界条件实现螺母的拧紧过程,输出过程动画和应力、位移参数 (3)提取螺栓中部截面的轴力和螺母拧紧力矩之间的关系 ,Abaqus; 螺栓拧紧; 参数化建模; 六面体C3D8R单元建模; 边界条件; 输出动画; 应力位移参数; 轴力与拧紧力矩关系。,Abaqus螺栓拧紧仿真:六面体单元建模与力矩关系分析
标题基于SpringBoot的汽车售后服务系统及微信小程序的设计与实现AI更换标题第1章引言介绍汽车售后服务的重要性,SpringBoot和微信小程序的应用背景,以及本研究的意义和目的。1.1研究背景与意义阐述汽车售后服务市场的现状及发展趋势,SpringBoot和微信小程序在售后服务中的应用前景。1.2国内外研究现状概述国内外在汽车售后服务系统和小程序开发方面的研究进展。1.3研究内容与创新点介绍本文的主要研究内容,包括系统设计和微信小程序的开发,并阐述创新点。第2章相关理论与技术介绍SpringBoot框架、微信小程序开发的相关理论和关键技术。2.1SpringBoot框架概述阐述SpringBoot框架的特点、优势以及在系统开发中的应用。2.2微信小程序开发技术介绍微信小程序的开发流程、关键技术和功能实现。2.3数据库技术与系统设计讨论数据库设计原则、数据存储和处理速度的问题,并阐述系统设计的思路和方法。第3章系统需求分析与设计对汽车售后服务系统的需求进行分析,并设计系统的整体架构和功能模块。3.1需求分析从用户角度和业务需求出发,对系统的功能需求和非功能需求进行详细分析。3.2
在智慧园区建设的浪潮中,一个集高效、安全、便捷于一体的综合解决方案正逐步成为现代园区管理的标配。这一方案旨在解决传统园区面临的智能化水平低、信息孤岛、管理手段落后等痛点,通过信息化平台与智能硬件的深度融合,为园区带来前所未有的变革。 首先,智慧园区综合解决方案以提升园区整体智能化水平为核心,打破了信息孤岛现象。通过构建统一的智能运营中心(IOC),采用1+N模式,即一个智能运营中心集成多个应用系统,实现了园区内各系统的互联互通与数据共享。IOC运营中心如同园区的“智慧大脑”,利用大数据可视化技术,将园区安防、机电设备运行、车辆通行、人员流动、能源能耗等关键信息实时呈现在拼接巨屏上,管理者可直观掌握园区运行状态,实现科学决策。这种“万物互联”的能力不仅消除了系统间的壁垒,还大幅提升了管理效率,让园区管理更加精细化、智能化。 更令人兴奋的是,该方案融入了诸多前沿科技,让智慧园区充满了未来感。例如,利用AI视频分析技术,智慧园区实现了对人脸、车辆、行为的智能识别与追踪,不仅极大提升了安防水平,还能为园区提供精准的人流分析、车辆管理等增值服务。同时,无人机巡查、巡逻机器人等智能设备的加入,让园区安全无死角,管理更轻松。特别是巡逻机器人,不仅能进行360度地面全天候巡检,还能自主绕障、充电,甚至具备火灾预警、空气质量检测等环境感知能力,成为了园区管理的得力助手。此外,通过构建高精度数字孪生系统,将园区现实场景与数字世界完美融合,管理者可借助VR/AR技术进行远程巡检、设备维护等操作,仿佛置身于一个虚拟与现实交织的智慧世界。 最值得关注的是,智慧园区综合解决方案还带来了显著的经济与社会效益。通过优化园区管理流程,实现降本增效。例如,智能库存管理、及时响应采购需求等举措,大幅减少了库存积压与浪费;而设备自动化与远程监控则降低了维修与人力成本。同时,借助大数据分析技术,园区可精准把握产业趋势,优化招商策略,提高入驻企业满意度与营收水平。此外,智慧园区的低碳节能设计,通过能源分析与精细化管理,实现了能耗的显著降低,为园区可持续发展奠定了坚实基础。总之,这一综合解决方案不仅让园区管理变得更加智慧、高效,更为入驻企业与员工带来了更加舒适、便捷的工作与生活环境,是未来园区建设的必然趋势。
c语言学习
人脸识别项目源码实战
人脸识别项目实战
内容概要:本文详细介绍了电力电子技术的基础知识及相关器件,内容涵盖电力电子器件(如晶闸管、GTR、IGBT)、相控整流电路(单相和三相)、直流斩波电路、交流变换电路、逆变电路、软开关技术等,并探讨了其应用场景(如开关电源、不间断电源(UPS)、电子镇流器、感应加热、直流电源、开关模焊接等),以及电力电子装置带来的电力公害(谐波污染、电磁干扰和功率因数降低)及其抑制方法。通过丰富的实例讲解了各类电路的工作原理和波形分析方法,旨在让学生和从业人员更好地理解和掌握该领域的核心技术和发展趋势。书中结合最新的研究成果进行了详尽阐述,使内容兼具科学性和创新性,并提供了大量习题以便于教与学。 适合人群:自动化、电气工程及其自动化等相关专业本科生、研究生和技术工程师。 使用场景及目标:①高校教师用于课堂授课,辅助学生深入理解电力电子器件工作原理;②电力电子领域科研人员和工程技术人员参考资料,掌握行业前沿技术和设计理念。 阅读建议:本文不仅讲解了电力电子器件的结构特点、操作流程,更重要的是展示了电力电子技术在整个电力系统和电气设备应用中的关键作用,希望读者能够在学习过程中理论结合实践,加深对知识的理解
c语言学习
万能视频拼接软件源码,可以直接进行修改增加功能,二次开发!
人脸识别项目源码实战
内容概要:本文介绍了FibroScan PRO这款专门用于肝脏纤维化程度评估的医疗器械。强调了其仅能被认证过的专员使用,所得到的数据需要专业医生综合考虑病人的实际身体状况进行精准解释。文中列举了若干组测量示例以及相关单位,例如压力数值(kPa)、声衰减参数(dB/m),还特别指出VCTE探针的正确性和精确度依靠定期校正。此外,详细阐述了病人的姿势调整以及测试部位选取的原则,在不同层厚的情况下对皮肤组织进行检查。并提供了一份详细的检查报告模板,涵盖了操作者的身份确认、受检人基本信息、时间戳以及其他一些量化评价指标,例如IQR(四分位距),这有助于更好地理解和应用FibroScan的检测结果。 适合人群:面向医院、诊所等相关医疗保健机构的工作人员,包括但不限于操作员和技术支持团队成员。同时也可以为想要了解这一先进诊断工具的研究人员或医学学生提供重要参考资料。 使用场景及目标:旨在指导医疗机构如何标准化地完成FibroScan设备的实际临床应用过程;确保所有测量数据均能在符合质量控制的前提下产生,并提高医疗服务的质量和效率;并且帮助医师做出更加科学合理的健康决策,最终服务于病患的利益最大化。