spring解析xml中的bean的一个关键类public class BeanDefinitionParserDelegate

package org.springframework.beans.factory.xml;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanMetadataAttribute;
import org.springframework.beans.BeanMetadataAttributeAccessor;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.ConstructorArgumentValues.ValueHolder;
import org.springframework.beans.factory.config.RuntimeBeanNameReference;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.beans.factory.parsing.BeanEntry;
import org.springframework.beans.factory.parsing.ConstructorArgumentEntry;
import org.springframework.beans.factory.parsing.ParseState;
import org.springframework.beans.factory.parsing.PropertyEntry;
import org.springframework.beans.factory.parsing.QualifierEntry;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.AutowireCandidateQualifier;
import org.springframework.beans.factory.support.BeanDefinitionDefaults;
import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.LookupOverride;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.ManagedProperties;
import org.springframework.beans.factory.support.ManagedSet;
import org.springframework.beans.factory.support.MethodOverrides;
import org.springframework.beans.factory.support.ReplaceOverride;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.DomUtils;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class BeanDefinitionParserDelegate
{
public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans";
public static final String BEAN_NAME_DELIMITERS = ",; ";
public static final String TRUE_VALUE = "true";
public static final String DEFAULT_VALUE = "default";
public static final String DESCRIPTION_ELEMENT = "description";
public static final String AUTOWIRE_BY_NAME_VALUE = "byName";
public static final String AUTOWIRE_BY_TYPE_VALUE = "byType";
public static final String AUTOWIRE_CONSTRUCTOR_VALUE = "constructor";
public static final String AUTOWIRE_AUTODETECT_VALUE = "autodetect";
public static final String DEPENDENCY_CHECK_ALL_ATTRIBUTE_VALUE = "all";
public static final String DEPENDENCY_CHECK_SIMPLE_ATTRIBUTE_VALUE = "simple";
public static final String DEPENDENCY_CHECK_OBJECTS_ATTRIBUTE_VALUE = "objects";
public static final String NAME_ATTRIBUTE = "name";
public static final String BEAN_ELEMENT = "bean";
public static final String META_ELEMENT = "meta";
public static final String ID_ATTRIBUTE = "id";
public static final String PARENT_ATTRIBUTE = "parent";
public static final String CLASS_ATTRIBUTE = "class";
public static final String ABSTRACT_ATTRIBUTE = "abstract";
public static final String SCOPE_ATTRIBUTE = "scope";
public static final String SINGLETON_ATTRIBUTE = "singleton";
public static final String LAZY_INIT_ATTRIBUTE = "lazy-init";
public static final String AUTOWIRE_ATTRIBUTE = "autowire";
public static final String AUTOWIRE_CANDIDATE_ATTRIBUTE = "autowire-candidate";
public static final String PRIMARY_ATTRIBUTE = "primary";
public static final String DEPENDENCY_CHECK_ATTRIBUTE = "dependency-check";
public static final String DEPENDS_ON_ATTRIBUTE = "depends-on";
public static final String INIT_METHOD_ATTRIBUTE = "init-method";
public static final String DESTROY_METHOD_ATTRIBUTE = "destroy-method";
public static final String FACTORY_METHOD_ATTRIBUTE = "factory-method";
public static final String FACTORY_BEAN_ATTRIBUTE = "factory-bean";
public static final String CONSTRUCTOR_ARG_ELEMENT = "constructor-arg";
public static final String INDEX_ATTRIBUTE = "index";
public static final String TYPE_ATTRIBUTE = "type";
public static final String VALUE_TYPE_ATTRIBUTE = "value-type";
public static final String KEY_TYPE_ATTRIBUTE = "key-type";
public static final String PROPERTY_ELEMENT = "property";
public static final String REF_ATTRIBUTE = "ref";
public static final String VALUE_ATTRIBUTE = "value";
public static final String LOOKUP_METHOD_ELEMENT = "lookup-method";
public static final String REPLACED_METHOD_ELEMENT = "replaced-method";
public static final String REPLACER_ATTRIBUTE = "replacer";
public static final String ARG_TYPE_ELEMENT = "arg-type";
public static final String ARG_TYPE_MATCH_ATTRIBUTE = "match";
public static final String REF_ELEMENT = "ref";
public static final String IDREF_ELEMENT = "idref";
public static final String BEAN_REF_ATTRIBUTE = "bean";
public static final String LOCAL_REF_ATTRIBUTE = "local";
public static final String PARENT_REF_ATTRIBUTE = "parent";
public static final String VALUE_ELEMENT = "value";
public static final String NULL_ELEMENT = "null";
public static final String LIST_ELEMENT = "list";
public static final String SET_ELEMENT = "set";
public static final String MAP_ELEMENT = "map";
public static final String ENTRY_ELEMENT = "entry";
public static final String KEY_ELEMENT = "key";
public static final String KEY_ATTRIBUTE = "key";
public static final String KEY_REF_ATTRIBUTE = "key-ref";
public static final String VALUE_REF_ATTRIBUTE = "value-ref";
public static final String PROPS_ELEMENT = "props";
public static final String PROP_ELEMENT = "prop";
public static final String MERGE_ATTRIBUTE = "merge";
public static final String QUALIFIER_ELEMENT = "qualifier";
public static final String QUALIFIER_ATTRIBUTE_ELEMENT = "attribute";
public static final String DEFAULT_LAZY_INIT_ATTRIBUTE = "default-lazy-init";
public static final String DEFAULT_MERGE_ATTRIBUTE = "default-merge";
public static final String DEFAULT_AUTOWIRE_ATTRIBUTE = "default-autowire";
public static final String DEFAULT_DEPENDENCY_CHECK_ATTRIBUTE = "default-dependency-check";
public static final String DEFAULT_AUTOWIRE_CANDIDATES_ATTRIBUTE = "default-autowire-candidates";
public static final String DEFAULT_INIT_METHOD_ATTRIBUTE = "default-init-method";
public static final String DEFAULT_DESTROY_METHOD_ATTRIBUTE = "default-destroy-method";
protected final Log logger = LogFactory.getLog(getClass());
private final XmlReaderContext readerContext;
private DocumentDefaultsDefinition defaults;
private ParseState parseState = new ParseState();

private final Set usedNames = new HashSet();

public BeanDefinitionParserDelegate(XmlReaderContext readerContext)
{
Assert.notNull(readerContext, "XmlReaderContext must not be null");
this.readerContext = readerContext;
}

public final XmlReaderContext getReaderContext()
{
return this.readerContext;
}

protected Object extractSource(Element ele)
{
return this.readerContext.extractSource(ele);
}

protected void error(String message, Node source)
{
this.readerContext.error(message, source, this.parseState.snapshot());
}

protected void error(String message, Element source)
{
this.readerContext.error(message, source, this.parseState.snapshot());
}

protected void error(String message, Element source, Throwable cause)
{
this.readerContext.error(message, source, this.parseState.snapshot(), cause);
}

public void initDefaults(Element root)
{
DocumentDefaultsDefinition defaults = new DocumentDefaultsDefinition();
defaults.setLazyInit(root.getAttribute("default-lazy-init"));
defaults.setMerge(root.getAttribute("default-merge"));
defaults.setAutowire(root.getAttribute("default-autowire"));
defaults.setDependencyCheck(root.getAttribute("default-dependency-check"));
if (root.hasAttribute("default-autowire-candidates")) {
defaults.setAutowireCandidates(root.getAttribute("default-autowire-candidates"));
}
if (root.hasAttribute("default-init-method")) {
defaults.setInitMethod(root.getAttribute("default-init-method"));
}
if (root.hasAttribute("default-destroy-method")) {
defaults.setDestroyMethod(root.getAttribute("default-destroy-method"));
}
defaults.setSource(this.readerContext.extractSource(root));

this.defaults = defaults;
this.readerContext.fireDefaultsRegistered(defaults);
}

public DocumentDefaultsDefinition getDefaults()
{
return this.defaults;
}

public BeanDefinitionDefaults getBeanDefinitionDefaults()
{
BeanDefinitionDefaults bdd = new BeanDefinitionDefaults();
if (this.defaults != null) {
bdd.setLazyInit("TRUE".equalsIgnoreCase(this.defaults.getLazyInit()));
bdd.setDependencyCheck(getDependencyCheck("default"));
bdd.setAutowireMode(getAutowireMode("default"));
bdd.setInitMethodName(this.defaults.getInitMethod());
bdd.setDestroyMethodName(this.defaults.getDestroyMethod());
}
return bdd;
}

public String[] getAutowireCandidatePatterns()
{
String candidatePattern = this.defaults.getAutowireCandidates();
return candidatePattern == null ? null : StringUtils.commaDelimitedListToStringArray(candidatePattern);
}

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele)
{
return parseBeanDefinitionElement(ele, null);
}

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean)
{
String id = ele.getAttribute("id");
String nameAttr = ele.getAttribute("name");

List aliases = new ArrayList();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, ",; ");
aliases.addAll(Arrays.asList(nameArr));
}

String beanName = id;
if ((!StringUtils.hasText(beanName)) && (!aliases.isEmpty())) {
beanName = (String)aliases.remove(0);
if (this.logger.isDebugEnabled()) {
this.logger.debug("No XML 'id' specified - using '" + beanName + "' as bean name and " + aliases + " as aliases");
}

}

if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}

AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, this.readerContext.getRegistry(), true);
}
else
{
beanName = this.readerContext.generateBeanName(beanDefinition);

String beanClassName = beanDefinition.getBeanClassName();
if ((beanClassName != null) && (beanName.startsWith(beanClassName)) && (beanName.length() > beanClassName.length()) && (!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)))
{
aliases.add(beanClassName);
}
}
if (this.logger.isDebugEnabled()) {
this.logger.debug("Neither XML 'id' nor 'name' specified - using generated bean name [" + beanName + "]");
}
}
catch (Exception ex)
{
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}

return null;
}

protected void checkNameUniqueness(String beanName, List aliases, Element beanElement)
{
String foundName = null;

if ((StringUtils.hasText(beanName)) && (this.usedNames.contains(beanName))) {
foundName = beanName;
}
if (foundName == null) {
foundName = (String)CollectionUtils.findFirstMatch(this.usedNames, aliases);
}
if (foundName != null) {
error("Bean name '" + foundName + "' is already used in this file", beanElement);
}

this.usedNames.add(beanName);
this.usedNames.addAll(aliases);
}

public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, BeanDefinition containingBean)
{
this.parseState.push(new BeanEntry(beanName));

String className = null;
if (ele.hasAttribute("class")) {
className = ele.getAttribute("class").trim();
}
try
{
String parent = null;
if (ele.hasAttribute("parent")) {
parent = ele.getAttribute("parent");
}
AbstractBeanDefinition bd = createBeanDefinition(className, parent);

parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, "description"));

parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);

bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));

AbstractBeanDefinition localAbstractBeanDefinition1 = bd;
return localAbstractBeanDefinition1;
}
catch (ClassNotFoundException ex)
{
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}

return null;
}

public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName, BeanDefinition containingBean, AbstractBeanDefinition bd)
{
if (ele.hasAttribute("scope"))
{
bd.setScope(ele.getAttribute("scope"));
if (ele.hasAttribute("singleton")) {
error("Specify either 'scope' or 'singleton', not both", ele);
}
}
else if (ele.hasAttribute("singleton"))
{
bd.setScope("true".equals(ele.getAttribute("singleton")) ? "singleton" : "prototype");
}
else if (containingBean != null)
{
bd.setScope(containingBean.getScope());
}

if (ele.hasAttribute("abstract")) {
bd.setAbstract("true".equals(ele.getAttribute("abstract")));
}

String lazyInit = ele.getAttribute("lazy-init");
if (("default".equals(lazyInit)) && (bd.isSingleton()))
{
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit("true".equals(lazyInit));

String autowire = ele.getAttribute("autowire");
bd.setAutowireMode(getAutowireMode(autowire));

String dependencyCheck = ele.getAttribute("dependency-check");
bd.setDependencyCheck(getDependencyCheck(dependencyCheck));

if (ele.hasAttribute("depends-on")) {
String dependsOn = ele.getAttribute("depends-on");
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, ",; "));
}

String autowireCandidate = ele.getAttribute("autowire-candidate");
if (("".equals(autowireCandidate)) || ("default".equals(autowireCandidate))) {
String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate("true".equals(autowireCandidate));
}

if (ele.hasAttribute("primary")) {
bd.setPrimary("true".equals(ele.getAttribute("primary")));
}

if (ele.hasAttribute("init-method")) {
String initMethodName = ele.getAttribute("init-method");
if (!"".equals(initMethodName)) {
bd.setInitMethodName(initMethodName);
}

}
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}

if (ele.hasAttribute("destroy-method")) {
String destroyMethodName = ele.getAttribute("destroy-method");
if (!"".equals(destroyMethodName)) {
bd.setDestroyMethodName(destroyMethodName);
}

}
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}

if (ele.hasAttribute("factory-method")) {
bd.setFactoryMethodName(ele.getAttribute("factory-method"));
}
if (ele.hasAttribute("factory-bean")) {
bd.setFactoryBeanName(ele.getAttribute("factory-bean"));
}

return bd;
}

protected AbstractBeanDefinition createBeanDefinition(String className, String parentName)
throws ClassNotFoundException
{
return BeanDefinitionReaderUtils.createBeanDefinition(parentName, className, this.readerContext.getBeanClassLoader());
}

public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor)
{
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "meta"))) {
Element metaElement = (Element)node;
String key = metaElement.getAttribute("key");
String value = metaElement.getAttribute("value");
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
}

public int getAutowireMode(String attValue) {
String att = attValue;
if ("default".equals(att)) {
att = this.defaults.getAutowire();
}
int autowire = 0;
if ("byName".equals(att)) {
autowire = 1;
}
else if ("byType".equals(att)) {
autowire = 2;
}
else if ("constructor".equals(att)) {
autowire = 3;
}
else if ("autodetect".equals(att)) {
autowire = 4;
}

return autowire;
}

public int getDependencyCheck(String attValue) {
String att = attValue;
if ("default".equals(att)) {
att = this.defaults.getDependencyCheck();
}
int dependencyCheckCode = 0;
if ("all".equals(att)) {
dependencyCheckCode = 3;
}
else if ("simple".equals(att)) {
dependencyCheckCode = 2;
}
else if ("objects".equals(att)) {
dependencyCheckCode = 1;
}

return dependencyCheckCode;
}

public void parseConstructorArgElements(Element beanEle, BeanDefinition bd)
{
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "constructor-arg")))
parseConstructorArgElement((Element)node, bd);
}
}

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 (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "property")))
parsePropertyElement((Element)node, bd);
}
}

public void parseQualifierElements(Element beanEle, AbstractBeanDefinition bd)
{
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "qualifier")))
parseQualifierElement((Element)node, bd);
}
}

public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides)
{
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "lookup-method"))) {
Element ele = (Element)node;
String methodName = ele.getAttribute("name");
String beanRef = ele.getAttribute("bean");
LookupOverride override = new LookupOverride(methodName, beanRef);
override.setSource(extractSource(ele));
overrides.addOverride(override);
}
}
}

public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides)
{
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "replaced-method"))) {
Element replacedMethodEle = (Element)node;
String name = replacedMethodEle.getAttribute("name");
String callback = replacedMethodEle.getAttribute("replacer");
ReplaceOverride replaceOverride = new ReplaceOverride(name, callback);

List argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, "arg-type");
for (Iterator it = argTypeEles.iterator(); it.hasNext(); ) {
Element argTypeEle = (Element)it.next();
replaceOverride.addTypeIdentifier(argTypeEle.getAttribute("match"));
}
replaceOverride.setSource(extractSource(replacedMethodEle));
overrides.addOverride(replaceOverride);
}
}
}

public void parseConstructorArgElement(Element ele, BeanDefinition bd)
{
String indexAttr = ele.getAttribute("index");
String typeAttr = ele.getAttribute("type");
if (StringUtils.hasLength(indexAttr))
try {
int index = Integer.parseInt(indexAttr);
if (index < 0)
error("'index' cannot be lower than 0", ele);
else
try
{
this.parseState.push(new ConstructorArgumentEntry(index));
Object value = parsePropertyValue(ele, bd, null);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
valueHolder.setSource(extractSource(ele));
bd.getConstructorArgumentValues().addIndexedArgumentValue(index, valueHolder);
}
finally {
this.parseState.pop();
}
}
catch (NumberFormatException ex)
{
error("Attribute 'index' of tag 'constructor-arg' must be an integer", ele);
}
else
try
{
this.parseState.push(new ConstructorArgumentEntry());
Object value = parsePropertyValue(ele, bd, null);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
valueHolder.setSource(extractSource(ele));
bd.getConstructorArgumentValues().addGenericArgumentValue(valueHolder);
}
finally {
this.parseState.pop();
}
}

public void parsePropertyElement(Element ele, BeanDefinition bd)
{
String propertyName = ele.getAttribute("name");
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();
}
}

public void parseQualifierElement(Element ele, AbstractBeanDefinition bd)
{
String typeName = ele.getAttribute("type");
if (!StringUtils.hasLength(typeName)) {
error("Tag 'qualifier' must have a 'type' attribute", ele);
return;
}
this.parseState.push(new QualifierEntry(typeName));
try {
AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(typeName);
qualifier.setSource(extractSource(ele));
String value = ele.getAttribute("value");
if (StringUtils.hasLength(value)) {
qualifier.setAttribute(AutowireCandidateQualifier.VALUE_KEY, value);
}
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (DomUtils.nodeNameEquals(node, "attribute"))) {
Element attributeEle = (Element)node;
String attributeName = attributeEle.getAttribute("key");
String attributeValue = attributeEle.getAttribute("value");
if ((StringUtils.hasLength(attributeName)) && (StringUtils.hasLength(attributeValue))) {
BeanMetadataAttribute attribute = new BeanMetadataAttribute(attributeName, attributeValue);
attribute.setSource(extractSource(attributeEle));
qualifier.addMetadataAttribute(attribute);
} else { error("Qualifier 'attribute' tag must have a 'name' and 'value'", attributeEle);
return;
}
}
}
bd.addQualifier(qualifier);
}
finally {
this.parseState.pop();
}
}

public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName)
{
String elementName = propertyName != null ? "<property> element for property '" + propertyName + "'" : "<constructor-arg> element";

NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if ((!(node instanceof Element)) || (DomUtils.nodeNameEquals(node, "description")) || (DomUtils.nodeNameEquals(node, "meta"))) {
continue;
}
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
subElement = (Element)node;
}

}

boolean hasRefAttribute = ele.hasAttribute("ref");
boolean hasValueAttribute = ele.hasAttribute("value");
if (((hasRefAttribute) && (hasValueAttribute)) || (((hasRefAttribute) || (hasValueAttribute)) && (subElement != null)))
{
error(elementName + " is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}

if (hasRefAttribute) {
String refName = ele.getAttribute("ref");
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(ele));
return ref;
}
if (hasValueAttribute) {
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute("value"));
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
if (subElement != null) {
return parsePropertySubElement(subElement, bd);
}

error(elementName + " must specify a ref or value", ele);
return null;
}

public Object parsePropertySubElement(Element ele, BeanDefinition bd)
{
return parsePropertySubElement(ele, bd, null);
}

public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultTypeClassName)
{
if (!isDefaultNamespace(ele.getNamespaceURI())) {
return parseNestedCustomElement(ele, bd);
}
if (DomUtils.nodeNameEquals(ele, "bean")) {
BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
if (nestedBd != null) {
nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
}
return nestedBd;
}
if (DomUtils.nodeNameEquals(ele, "ref"))
{
String refName = ele.getAttribute("bean");
boolean toParent = false;
if (!StringUtils.hasLength(refName))
{
refName = ele.getAttribute("local");
if (!StringUtils.hasLength(refName))
{
refName = ele.getAttribute("parent");
toParent = true;
if (!StringUtils.hasLength(refName)) {
error("'bean', 'local' or 'parent' is required for <ref> element", ele);
return null;
}
}
}
if (!StringUtils.hasText(refName)) {
error("<ref> element contains empty target attribute", ele);
return null;
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
ref.setSource(extractSource(ele));
return ref;
}
if (DomUtils.nodeNameEquals(ele, "idref")) {
return parseIdRefElement(ele);
}
if (DomUtils.nodeNameEquals(ele, "value")) {
return parseValueElement(ele, defaultTypeClassName);
}
if (DomUtils.nodeNameEquals(ele, "null"))
{
TypedStringValue nullHolder = new TypedStringValue(null);
nullHolder.setSource(extractSource(ele));
return nullHolder;
}
if (DomUtils.nodeNameEquals(ele, "list")) {
return parseListElement(ele, bd);
}
if (DomUtils.nodeNameEquals(ele, "set")) {
return parseSetElement(ele, bd);
}
if (DomUtils.nodeNameEquals(ele, "map")) {
return parseMapElement(ele, bd);
}
if (DomUtils.nodeNameEquals(ele, "props")) {
return parsePropsElement(ele);
}

error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
return null;
}

public Object parseIdRefElement(Element ele)
{
String refName = ele.getAttribute("bean");
if (!StringUtils.hasLength(refName))
{
refName = ele.getAttribute("local");
if (!StringUtils.hasLength(refName)) {
error("Either 'bean' or 'local' is required for <idref> element", ele);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error("<idref> element contains empty target attribute", ele);
return null;
}
RuntimeBeanNameReference ref = new RuntimeBeanNameReference(refName);
ref.setSource(extractSource(ele));
return ref;
}

public Object parseValueElement(Element ele, String defaultTypeClassName)
{
String value = DomUtils.getTextValue(ele);
String typeClassName = ele.getAttribute("type");
if (!StringUtils.hasText(typeClassName))
typeClassName = defaultTypeClassName;
try
{
return buildTypedStringValue(value, typeClassName, ele);
}
catch (ClassNotFoundException ex) {
error("Type class [" + typeClassName + "] not found for <value> element", ele, ex);
}return value;
}

protected Object buildTypedStringValue(String value, String targetTypeName, Element ele)
throws ClassNotFoundException
{
ClassLoader classLoader = this.readerContext.getBeanClassLoader();
TypedStringValue typedValue = null;
if (!StringUtils.hasText(targetTypeName)) {
typedValue = new TypedStringValue(value);
}
else if (classLoader != null) {
Class targetType = ClassUtils.forName(targetTypeName, classLoader);
typedValue = new TypedStringValue(value, targetType);
}
else {
typedValue = new TypedStringValue(value, targetTypeName);
}
typedValue.setSource(extractSource(ele));
return typedValue;
}

public List parseListElement(Element collectionEle, BeanDefinition bd)
{
String defaultTypeClassName = collectionEle.getAttribute("value-type");
NodeList nl = collectionEle.getChildNodes();
ManagedList list = new ManagedList(nl.getLength());
list.setSource(extractSource(collectionEle));
list.setMergeEnabled(parseMergeAttribute(collectionEle));
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (!DomUtils.nodeNameEquals(node, "description"))) {
list.add(parsePropertySubElement((Element)node, bd, defaultTypeClassName));
}
}
return list;
}

public Set parseSetElement(Element collectionEle, BeanDefinition bd)
{
String defaultTypeClassName = collectionEle.getAttribute("value-type");
NodeList nl = collectionEle.getChildNodes();
ManagedSet set = new ManagedSet(nl.getLength());
set.setSource(extractSource(collectionEle));
set.setMergeEnabled(parseMergeAttribute(collectionEle));
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (((node instanceof Element)) && (!DomUtils.nodeNameEquals(node, "description"))) {
set.add(parsePropertySubElement((Element)node, bd, defaultTypeClassName));
}
}
return set;
}

public Map parseMapElement(Element mapEle, BeanDefinition bd)
{
String defaultKeyTypeClassName = mapEle.getAttribute("key-type");
String defaultValueTypeClassName = mapEle.getAttribute("value-type");

List entryEles = DomUtils.getChildElementsByTagName(mapEle, "entry");
ManagedMap map = new ManagedMap(entryEles.size());
map.setMergeEnabled(parseMergeAttribute(mapEle));
map.setSource(extractSource(mapEle));

for (Iterator it = entryEles.iterator(); it.hasNext(); ) {
Element entryEle = (Element)it.next();

NodeList entrySubNodes = entryEle.getChildNodes();

Element keyEle = null;
Element valueEle = null;
for (int j = 0; j < entrySubNodes.getLength(); j++) {
Node node = entrySubNodes.item(j);
if ((node instanceof Element)) {
Element candidateEle = (Element)node;
if (DomUtils.nodeNameEquals(candidateEle, "key")) {
if (keyEle != null) {
error("<entry> element is only allowed to contain one <key> sub-element", entryEle);
}
else {
keyEle = candidateEle;
}

}
else if (valueEle != null) {
error("<entry> element must not contain more than one value sub-element", entryEle);
}
else {
valueEle = candidateEle;
}

}

}

Object key = null;
boolean hasKeyAttribute = entryEle.hasAttribute("key");
boolean hasKeyRefAttribute = entryEle.hasAttribute("key-ref");
if (((hasKeyAttribute) && (hasKeyRefAttribute)) || (((hasKeyAttribute) || (hasKeyRefAttribute)) && (keyEle != null)))
{
error("<entry> element is only allowed to contain either a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle);
}

if (hasKeyAttribute) {
key = buildTypedStringValueForMap(entryEle.getAttribute("key"), defaultKeyTypeClassName, entryEle);
}
else if (hasKeyRefAttribute) {
String refName = entryEle.getAttribute("key-ref");
if (!StringUtils.hasText(refName)) {
error("<entry> element contains empty 'key-ref' attribute", entryEle);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle));
key = ref;
}
else if (keyEle != null) {
key = parseKeyElement(keyEle, bd, defaultKeyTypeClassName);
}
else {
error("<entry> element must specify a key", entryEle);
}

Object value = null;
boolean hasValueAttribute = entryEle.hasAttribute("value");
boolean hasValueRefAttribute = entryEle.hasAttribute("value-ref");
if (((hasValueAttribute) && (hasValueRefAttribute)) || (((hasValueAttribute) || (hasValueRefAttribute)) && (valueEle != null)))
{
error("<entry> element is only allowed to contain either 'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle);
}

if (hasValueAttribute) {
value = buildTypedStringValueForMap(entryEle.getAttribute("value"), defaultValueTypeClassName, entryEle);
}
else if (hasValueRefAttribute) {
String refName = entryEle.getAttribute("value-ref");
if (!StringUtils.hasText(refName)) {
error("<entry> element contains empty 'value-ref' attribute", entryEle);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle));
value = ref;
}
else if (valueEle != null) {
value = parsePropertySubElement(valueEle, bd, defaultValueTypeClassName);
}
else {
error("<entry> element must specify a value", entryEle);
}

map.put(key, value);
}

return map;
}

protected final Object buildTypedStringValueForMap(String value, String defaultTypeClassName, Element entryEle)
{
try
{
return buildTypedStringValue(value, defaultTypeClassName, entryEle);
}
catch (ClassNotFoundException ex) {
error("Type class [" + defaultTypeClassName + "] not found for Map key/value type", entryEle, ex);
}return value;
}

public Object parseKeyElement(Element keyEle, BeanDefinition bd, String defaultKeyTypeClassName)
{
NodeList nl = keyEle.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (!(node instanceof Element))
continue;
if (subElement != null) {
error("<key> element must not contain more than one value sub-element", keyEle);
}
else {
subElement = (Element)node;
}
}

return parsePropertySubElement(subElement, bd, defaultKeyTypeClassName);
}

public Properties parsePropsElement(Element propsEle)
{
ManagedProperties props = new ManagedProperties();
props.setSource(extractSource(propsEle));
props.setMergeEnabled(parseMergeAttribute(propsEle));

List propEles = DomUtils.getChildElementsByTagName(propsEle, "prop");
for (Iterator it = propEles.iterator(); it.hasNext(); ) {
Element propEle = (Element)it.next();
String key = propEle.getAttribute("key");

String value = DomUtils.getTextValue(propEle).trim();

TypedStringValue keyHolder = new TypedStringValue(key);
keyHolder.setSource(extractSource(propEle));
TypedStringValue valueHolder = new TypedStringValue(value);
valueHolder.setSource(extractSource(propEle));
props.put(keyHolder, valueHolder);
}

return props;
}

public boolean parseMergeAttribute(Element collectionElement)
{
String value = collectionElement.getAttribute("merge");
if ("default".equals(value)) {
value = this.defaults.getMerge();
}
return "true".equals(value);
}

public BeanDefinition parseCustomElement(Element ele) {
return parseCustomElement(ele, null);
}

public BeanDefinition parseCustomElement(Element ele, BeanDefinition containingBd) {
String namespaceUri = ele.getNamespaceURI();
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler == null) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
return null;
}
return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
}

public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder) {
return decorateBeanDefinitionIfRequired(ele, definitionHolder, null);
}

public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder, BeanDefinition containingBd)
{
BeanDefinitionHolder finalDefinition = definitionHolder;

NamedNodeMap attributes = ele.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}

NodeList children = ele.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
if (node.getNodeType() == 1) {
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
}
return finalDefinition;
}

private BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef, BeanDefinition containingBd)
{
String namespaceUri = node.getNamespaceURI();
if (!isDefaultNamespace(namespaceUri)) {
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler != null) {
return handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
}
if (namespaceUri.startsWith("http://www.springframework.org/")) {
error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", node);
}
else if (this.logger.isDebugEnabled()) {
this.logger.debug("No Spring NamespaceHandler found for XML schema namespace [" + namespaceUri + "]");
}
}

return originalDef;
}

public boolean isDefaultNamespace(String namespaceUri) {
return (!StringUtils.hasLength(namespaceUri)) || ("http://www.springframework.org/schema/beans".equals(namespaceUri));
}

private BeanDefinitionHolder parseNestedCustomElement(Element ele, BeanDefinition containingBd) {
BeanDefinition innerDefinition = parseCustomElement(ele, containingBd);
if (innerDefinition == null) {
error("Incorrect usage of element '" + ele.getNodeName() + "' in a nested manner. " + "This tag cannot be used nested inside <property>.", ele);

return null;
}
String id = ele.getNodeName() + "#" + ObjectUtils.getIdentityHexString(innerDefinition);

if (this.logger.isDebugEnabled()) {
this.logger.debug("Using generated bean name [" + id + "] for nested custom element '" + ele.getNodeName() + "'");
}

return new BeanDefinitionHolder(innerDefinition, id);
}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值