1.0 Property子元素的使用

  property 子元素是再常用不过的了, 在看Spring源码之前,我们先看看它的使用方法,

1. 实例类如下:

 public class Animal {

     public String type;

     public Set<Integer> age;

     private Map<String, Integer> sell;

     public Animal() {

     }

     /**
* @return the type
*/
public String getType() {
return type;
} /**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
} /**
* @return the age
*/
public Set<Integer> getAge() {
return age;
} /**
* @param age the age to set
*/
public void setAge(Set<Integer> age) {
this.age = age;
} /**
* @return the sell
*/
public Map<String, Integer> getSell() {
return sell;
} /**
* @param sell the sell to set
*/
public void setSell(Map<String, Integer> sell) {
this.sell = sell;
} /*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Animal [type=" + type + ", age=" + age + ", sell=" + sell + "]";
} }

xml如下,

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="animal" class="test.property.Animal">
<property name="type" value="cat"></property>
<property name="age">
<set>
<value>1</value>
<value>2</value>
<value>3</value>
</set>
</property>
<property name="sell">
<map>
<entry key="blue" value="111"></entry>
<entry key="red" value="22"></entry>
</map>
</property>
</bean>
</beans>

测试类如下:

 public class Main {

     public static String XML_PATH = "test\\property\\applicationContxt.xml";

     public static void main(String[] args) {
try {
Resource resource = new ClassPathResource(XML_PATH);
XmlBeanFactory beanFactory = new XmlBeanFactory(resource);
Animal bean = (Animal) beanFactory.getBean("animal");
System.out.println(bean);
}
catch (Exception e) {
e.printStackTrace();
}
}
}

控制台输出的结果为

Animal [type=cat, age=[1, 2, 3], sell={blue=111, red=22}]

2.0 Spring具体的解析过程为:

  2.1

 /**
* Parse property sub-elements of the given bean element.
*/
public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
// 这里进去
parsePropertyElement((Element) node, bd);
}
}
}

  2.2

 /**
* Parse a property element.
*/
public void parsePropertyElement(Element ele, BeanDefinition bd) {
// 获取配置文件中name 的值
String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
if (!StringUtils.hasLength(propertyName)) {
error("Tag 'property' must have a 'name' attribute", ele);
return;
}
this.parseState.push(new PropertyEntry(propertyName));
try {
// 不容许多次对同一属性配置
if (bd.getPropertyValues().contains(propertyName)) {
error("Multiple 'property' definitions for property '" + propertyName
+ "'", ele);
return;
}
Object val = parsePropertyValue(ele, bd, propertyName);
PropertyValue pv = new PropertyValue(propertyName, val);
parseMetaElements(ele, pv);
pv.setSource(extractSource(ele));
bd.getPropertyValues().addPropertyValue(pv);
}
finally {
this.parseState.pop();
}
}

  2.3 然后又回到parsePropertyValue 方法了

 public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
String elementName = (propertyName != null) ? "<property> element for property '"
+ propertyName + "'" : "<constructor-arg> element"; // Should only have one child element: ref, value, list, etc.
// 应该只有一个子元素:REF,值,列表等。
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
// 对应的description 或者meta不处理
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)
&& !nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element",
ele);
}
else {
subElement = (Element) node;
}
}
}
// 解析 ref
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
// 解析 value
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
if ((hasRefAttribute && hasValueAttribute)
|| ((hasRefAttribute || hasValueAttribute) && subElement != null)) {
/*
* 1.不能同时有ref 又有 value 2.不能存在ref 或者 value 又有子元素
*/
error(elementName
+ " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element",
ele);
} if (hasRefAttribute) {
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
// ref 属性的处理 , 使用RuntimeBeanReference封装对应的ref名称
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(ele));
return ref;
}
else if (hasValueAttribute) {
// Value 属性的处理 , 使用TypedStringValue封装对应的
TypedStringValue valueHolder = new TypedStringValue(
ele.getAttribute(VALUE_ATTRIBUTE));
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
else if (subElement != null) {
// 解析子元素
return parsePropertySubElement(subElement, bd);
}
else {
// Neither child element nor "ref" or "value" attribute found.
// 对于没有ref 也没有子元素的,Spring只好丢出异常
error(elementName + " must specify a ref or value", ele);
return null;
}
}

这里之前构造函数的解析那里已经讲得很详细了,这里不多做解释,不同的是返回值使用PropertyValue 封装,并且记录在BeanDefinition 的 propertyValues属性当中.

3.7 spring-property 子元素的使用与解析的更多相关文章

  1. 3.6 spring-construction-arg 子元素的使用与解析

    对于构造函数子元素是非常常用的. 相信大家也一定不陌生, 举个小例子: public class Animal { public String type; public int age; /** * ...

  2. 3.5 spring-replaced-method 子元素的使用与解析

    1.replaced-method 子元素 方法替换: 可以在运行时用新的方法替换现有的方法,与之前的 look-up不同的是replace-method 不但可以动态地替换返回的实体bean,而且可 ...

  3. 3.4 spring- lookup-method 子元素的使用与解析

    1. lookup-method的应用: 1.1 子元素lookup-method 似乎不是很常用,但是在某些时候他的确是非常有用的属性,通常我们称它为 "获取器注入" . 引用 ...

  4. 3.8 spring-qualifier 子元素的使用与解析

      对于 qualifier 子元素,我们接触的更多的是注解形式,在使用Spring 自动注入时,Spring 容器中匹配的候选 Bean 数目必须有且仅有一个.当找不到一个匹配的 Bean 时, S ...

  5. 3.3 spring-meta子元素的使用与解析

    1. meta元素的使用 在解析元数据的分析之前,我们先回顾一下 meta属性的使用: <bean id="car" class="test.CarFactoryB ...

  6. Spring 系列教程之默认标签的解析

    Spring 系列教程之默认标签的解析 之前提到过 Spring 中的标签包括默认标签和自定义标签两种,而两种标签的用法以及解析方式存在着很大的不同,本章节重点带领读者详细分析默认标签的解析过程. 默 ...

  7. Spring框架之beans源码完全解析

    导读:Spring可以说是Java企业开发里最重要的技术.而Spring两大核心IOC(Inversion of Control控制反转)和AOP(Aspect Oriented Programmin ...

  8. spring bean属性及子元素使用总结

    spring bean属性及子元素使用总结 2016-08-03 00:00 97人阅读 评论(0) 收藏 举报  分类: Spring&SpringMVC(17)  版权声明:本文为博主原创 ...

  9. Spring 配置文件中 元素 属性 说明

    <beans /> 元素 该元素是根元素.<bean /> 元素的属性 default-init // 是否开启懒加载.默认为 false default-dependency ...

随机推荐

  1. 织梦dedecms源码安装方法

    织梦dedecms源码安装方法 第一步: 上传所有文件到空间 注意:(由于有很多人反应安装后首页样式都乱的,所以强烈要求安装到根目录,如:127.0.0.1 / www.xxx.com,或者二级域名也 ...

  2. MyEclipse8.5集成Tomcat7时的启动错误:Exception in thread “main” java.lang.NoClassDefFoundError org/apache/commons/logging/LogFactory

    今天,安装Tomcat7.0.21后,单独用D:\apache-tomcat-7.0.21\bin\startup.bat启动web服务正常.但 在MyEclipse8.5中集成配置Tomcat7后, ...

  3. 刚更新的css hack技巧

    一 一般Hack 1概念: 不同的浏览器对CSS的解析效果不同,为了达到相同的效果,就得根据不同浏览器写不同的css 2规则: CSS Hack大致有3种表现形式,CSS类内部Hack.选择器Hack ...

  4. Lombok(1.14.8) - @Synchronized

    @Synchronized @Synchronized,实现同步. package com.huey.lombok; import java.util.Date; import lombok.Sync ...

  5. 浅谈Oracle 性能优化

    基于大型Oracle数据库应用开发已有6个年头了,经历了从最初零数据演变到目前上亿级的数据存储.在这个经历中,遇到各种各样的性能问题及各种性能优化. 在这里主要给大家分享一下数据库性能优化的一些方法和 ...

  6. 【网络收集】Sql Server datetime 常用日期格式转换

    ) , sfrq, ) 我们经常出于某种目的需要使用各种各样的日期格式,当然我们可以使用字符串操作来构造各种日期格式,但是有现成的函数为什么不用呢? SQL Server中文版的默认的日期字段date ...

  7. Linux 最常用命令小结

    1. 文件共享 1).将windows 系统下的文件夹共享到linux的方法: 安装filezilla,设置连接linux 服务器.将文件上传. 2).mRemote 机器连接管理 2. 文件管理命令 ...

  8. 第三十篇、iOS开发中常用的宏

    //字符串是否为空 #define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str leng ...

  9. 暑假集训(4)第四弹 -----排列,计数(hdu1465)

    题意概括:嗯,纵使你数次帮助小A脱离困境,但上一次,小A终于还是失败了.那数年的奔波与心血,抵不过轻轻一指,便彻底 湮灭,多年的友谊终归走向末路.这一切重击把小A彻底击溃! 不为什么,你到底还是要继续 ...

  10. Bugzilla+MySql+IIS+ActivePerl搭建指南

    头在忙着他的技术研究,对团队建设.测试管理.流程规范都不怎么理会,眼见着产品进入后期整合阶段,在测试过错中出现很多Bug,单靠着我一个人用txt来收集整理bug需求,然后整理成word,放在svn上面 ...