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

时间:2024-01-05 17:57:44

1. meta元素的使用

在解析元数据的分析之前,我们先回顾一下 meta属性的使用:

<bean id="car" class="test.CarFactoryBean">
<property name="carInfo" value="超级跑车,400,2000000"/>
  <meta key = "key" value = "values">
</bean>

这段代码并不会体现在 CarFactoryBean 的属性当中,而是一个额外的声明,当需要里面的属性时,可以通过BeanDefinition的getAttribute(key);方法获取,

  对meta属性解析的代码如下:

beans/src/main/java/org/springframework/beans/factory/xml/BeanDefinitionParserDelegate.java

 public void parseMetaElements(Element ele,
BeanMetadataAttributeAccessor attributeAccessor) {
// 获取当前节点下的所有子元素
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
// 提取meta
if (isCandidateElement(node) && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
// 使用 key,value 构造 BeanMetadataAttribute
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
// 记录信息
attributeAccessor.addMetadataAttribute(attribute);
}
}
}