CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-springframework--spring-beans

Spring Beans - IoC Container and Dependency Injection providing comprehensive bean management infrastructure and dependency injection capabilities.

Pending
Overview
Eval results
Files

xml-config.mddocs/

XML Configuration Support

Extensible XML parsing framework with namespace support, custom schema handling, and comprehensive bean definition loading from XML configuration files. This system enables declarative configuration of Spring beans through XML files with support for custom namespaces and validation.

Capabilities

XML Bean Definition Reader

Core class for reading bean definitions from XML configuration files with support for validation, namespace handling, and custom schema resolution.

/**
 * Bean definition reader for XML bean definitions, using a SAX parser under the hood.
 */
class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {
    /** Indicates that no validation should be performed. */
    public static final int VALIDATION_NONE = XmlValidationModeDetector.VALIDATION_NONE;
    /** Indicates that an XSD should be used for validation if a schema declaration is found. */
    public static final int VALIDATION_AUTO = XmlValidationModeDetector.VALIDATION_AUTO;
    /** Indicates that DTD validation should be performed. */
    public static final int VALIDATION_DTD = XmlValidationModeDetector.VALIDATION_DTD;
    /** Indicates that XSD validation should be performed. */
    public static final int VALIDATION_XSD = XmlValidationModeDetector.VALIDATION_XSD;
    
    /**
     * Create new XmlBeanDefinitionReader for the given bean factory.
     * @param registry the BeanFactory to load bean definitions into
     */
    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry);
    
    /**
     * Set whether to use XML validation.
     * @param validating whether to validate; switches off validation otherwise
     */
    public void setValidating(boolean validating);
    
    /**
     * Set the validation mode to use by name.
     * @param validationModeName the validation mode name
     */
    public void setValidationModeName(String validationModeName);
    
    /**
     * Set the validation mode to use.
     * @param validationMode the validation mode
     */
    public void setValidationMode(int validationMode);
    
    /**
     * Return the validation mode to use.
     * @return the validation mode
     */
    public int getValidationMode();
    
    /**
     * Set whether or not the XML parser should be XML namespace aware.
     * @param namespaceAware the default is false
     */
    public void setNamespaceAware(boolean namespaceAware);
    
    /**
     * Return whether or not the XML parser should be XML namespace aware.
     * @return true if namespace aware
     */
    public boolean isNamespaceAware();
    
    /**
     * Set an implementation of the ProblemReporter interface to use.
     * @param problemReporter the desired ProblemReporter implementation
     */
    public void setProblemReporter(ProblemReporter problemReporter);
    
    /**
     * Set an implementation of the ReaderEventListener interface to use.
     * @param eventListener the desired ReaderEventListener implementation
     */
    public void setEventListener(ReaderEventListener eventListener);
    
    /**
     * Set the SourceExtractor to use for generated bean definitions that correspond to top-level beans.
     * @param sourceExtractor the desired SourceExtractor implementation
     */
    public void setSourceExtractor(SourceExtractor sourceExtractor);
    
    /**
     * Set the NamespaceHandlerResolver to use.
     * @param namespaceHandlerResolver the desired NamespaceHandlerResolver implementation
     */
    public void setNamespaceHandlerResolver(NamespaceHandlerResolver namespaceHandlerResolver);
    
    /**
     * Set the DocumentLoader to use for loading XML documents.
     * @param documentLoader the desired DocumentLoader implementation
     */
    public void setDocumentLoader(DocumentLoader documentLoader);
    
    /**
     * Set the EntityResolver to use for resolving DTDs and schemas.
     * @param entityResolver the desired EntityResolver implementation
     */
    public void setEntityResolver(EntityResolver entityResolver);
    
    /**
     * Set the ErrorHandler to use for handling XML parsing errors.
     * @param errorHandler the desired ErrorHandler implementation
     */
    public void setErrorHandler(ErrorHandler errorHandler);
    
    /**
     * Load bean definitions from the specified XML file.
     * @param resource the resource descriptor for the XML file
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException;
    
    /**
     * Load bean definitions from the specified XML file.
     * @param encodedResource the resource descriptor for the XML file, allowing to specify an encoding to use for parsing the file
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException;
    
    /**
     * Load bean definitions from the specified XML file.
     * @param inputSource the SAX InputSource to read from
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    public int loadBeanDefinitions(InputSource inputSource) throws BeanDefinitionStoreException;
    
    /**
     * Load bean definitions from the specified XML file.
     * @param inputSource the SAX InputSource to read from
     * @param resource the resource descriptor for the XML file
     * @return the number of bean definitions found
     * @throws BeanDefinitionStoreException in case of loading or parsing errors
     */
    public int loadBeanDefinitions(InputSource inputSource, Resource resource) throws BeanDefinitionStoreException;
}

Bean Definition Document Reader

Interface and implementation for reading bean definitions from XML documents.

/**
 * SPI for parsing an XML document that contains Spring bean definitions.
 */
interface BeanDefinitionDocumentReader {
    /**
     * Read bean definitions from the given DOM document and register them with the given bean definition registry.
     * @param doc the DOM document
     * @param readerContext the current context of the reader (includes the target registry and the resource being parsed)
     * @throws BeanDefinitionStoreException in case of parsing errors
     */
    void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) throws BeanDefinitionStoreException;
}

/**
 * Default implementation of BeanDefinitionDocumentReader that reads bean definitions according to the "spring-beans" DTD and XSD format.
 */
class DefaultBeanDefinitionDocumentReader implements BeanDefinitionDocumentReader {
    /** Constant for the "bean" element. */
    public static final String BEAN_ELEMENT = BeanDefinitionParserDelegate.BEAN_ELEMENT;
    /** Constant for the "beans" element. */
    public static final String NESTED_BEANS_ELEMENT = "beans";
    /** Constant for the "alias" element. */
    public static final String ALIAS_ELEMENT = "alias";
    /** Constant for the "name" attribute. */
    public static final String NAME_ATTRIBUTE = "name";
    /** Constant for the "alias" attribute. */
    public static final String ALIAS_ATTRIBUTE = "alias";
    /** Constant for the "import" element. */
    public static final String IMPORT_ELEMENT = "import";
    /** Constant for the "resource" attribute. */
    public static final String RESOURCE_ATTRIBUTE = "resource";
    /** Constant for the "profile" attribute. */
    public static final String PROFILE_ATTRIBUTE = "profile";
    
    /**
     * This implementation parses bean definitions according to the "spring-beans" XSD (or DTD, historically).
     * @param doc the DOM document
     * @param readerContext the current context of the reader
     */
    public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext);
}

Bean Definition Parser Delegate

Stateful delegate class used to parse XML bean definitions.

/**
 * Stateful delegate class used to parse XML bean definitions.
 */
class BeanDefinitionParserDelegate {
    /** Constant for the Spring beans namespace URI. */
    public static final String BEANS_NAMESPACE_URI = "http://www.springframework.org/schema/beans";
    /** Constant for the default delimiters for multiple values in a single attribute. */
    public static final String MULTI_VALUE_ATTRIBUTE_DELIMITERS = ",; ";
    /** Constant for the "true" value. */
    public static final String TRUE_VALUE = "true";
    /** Constant for the "false" value. */
    public static final String FALSE_VALUE = "false";
    /** Constant for the "default" value. */
    public static final String DEFAULT_VALUE = "default";
    /** Constant for the "bean" element. */
    public static final String BEAN_ELEMENT = "bean";
    /** Constant for the "description" element. */
    public static final String DESCRIPTION_ELEMENT = "description";
    /** Constant for the "import" element. */
    public static final String IMPORT_ELEMENT = "import";
    /** Constant for the "alias" element. */
    public static final String ALIAS_ELEMENT = "alias";
    
    /**
     * Create a new BeanDefinitionParserDelegate associated with the supplied XmlReaderContext.
     * @param readerContext the XML reader context
     */
    public BeanDefinitionParserDelegate(XmlReaderContext readerContext);
    
    /**
     * Get the XmlReaderContext associated with this delegate.
     * @return the XmlReaderContext
     */
    public final XmlReaderContext getReaderContext();
    
    /**
     * Initialize the default lazy-init, autowire, dependency check settings, init-method, destroy-method and merge settings.
     * @param root the root element of the current bean definition document (or nested beans element)
     */
    public void initDefaults(Element root);
    
    /**
     * Initialize the default settings.
     * @param root the root element of the current bean definition document (or nested beans element)
     * @param parent the parent bean definition parser delegate (if any)
     */
    public void initDefaults(Element root, BeanDefinitionParserDelegate parent);
    
    /**
     * Return the defaults definition object.
     * @return the defaults definition object
     */
    public DocumentDefaultsDefinition getDefaults();
    
    /**
     * Return the default settings for bean definitions as BeanDefinitionDefaults object.
     * @return the BeanDefinitionDefaults object
     */
    public BeanDefinitionDefaults getBeanDefinitionDefaults();
    
    /**
     * Return any patterns provided in the 'default-autowire-candidates' attribute of the top-level beans element.
     * @return the autowire candidate patterns, or null if none specified
     */
    public String[] getAutowireCandidatePatterns();
    
    /**
     * Parses the supplied Element and creates a BeanDefinition by delegating to the createBeanDefinition method.
     * @param ele the element that is to be parsed into a BeanDefinition
     * @return the BeanDefinition
     */
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele);
    
    /**
     * Parses the supplied Element and creates a BeanDefinition by delegating to the createBeanDefinition method.
     * @param ele the element that is to be parsed into a BeanDefinition
     * @param containingBean the containing bean definition (if any)
     * @return the BeanDefinition
     */
    public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean);
    
    /**
     * Create a bean definition for the given class name and parent name.
     * @param className the name of the bean class
     * @param parentName the name of the parent bean
     * @return the newly created bean definition
     * @throws ClassNotFoundException if bean class resolution was attempted but failed
     */
    public AbstractBeanDefinition createBeanDefinition(String className, String parentName) throws ClassNotFoundException;
    
    /**
     * Parse the meta elements underneath the given element, if any.
     * @param ele the DOM element we're parsing
     * @param attributeAccessor the BeanMetadataAttributeAccessor to attach the metadata to
     */
    public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor);
    
    /**
     * Parse the lookup-method elements.
     * @param beanElement the current bean element
     * @param bd the current bean definition
     */
    public void parseLookupOverrideSubElements(Element beanElement, MethodOverrides overrides);
    
    /**
     * Parse replaced-method elements.
     * @param beanElement the current bean element
     * @param bd the current bean definition
     */
    public void parseReplacedMethodSubElements(Element beanElement, MethodOverrides overrides);
    
    /**
     * Parse constructor-arg elements.
     * @param beanElement the current bean element
     * @param bd the current bean definition
     */
    public void parseConstructorArgElements(Element beanElement, BeanDefinition bd);
    
    /**
     * Parse property elements.
     * @param beanElement the current bean element
     * @param bd the current bean definition
     */
    public void parsePropertyElements(Element beanElement, BeanDefinition bd);
    
    /**
     * Parse qualifier elements.
     * @param beanElement the current bean element
     * @param bd the current bean definition
     */
    public void parseQualifierElements(Element beanElement, AbstractBeanDefinition bd);
    
    /**
     * Get the value of a property element.
     * @param ele the property element
     * @param bd the current bean definition
     * @param propertyName the name of the property represented by this element
     * @return the Object value
     */
    public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName);
    
    /**
     * Parse a value, ref or any of the collection elements.
     * @param ele the current property element
     * @param bd the current bean definition
     * @return the parsed Object
     */
    public Object parsePropertySubElement(Element ele, BeanDefinition bd);
    
    /**
     * Parse a value, ref or any of the collection elements.
     * @param ele the current property element
     * @param bd the current bean definition
     * @param defaultValueType the default type (class name) for any <value> tag that might be created
     * @return the parsed Object
     */
    public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType);
}

Namespace Handler Support

Framework for handling custom XML namespaces in Spring configuration files.

/**
 * Base interface used by the DefaultBeanDefinitionDocumentReader for handling custom namespaces in a Spring XML configuration file.
 */
interface NamespaceHandler {
    /**
     * Invoked by the DefaultBeanDefinitionDocumentReader after construction but before any custom elements are parsed.
     */
    void init();
    
    /**
     * Parse the specified Element and register any resulting BeanDefinitions with the BeanDefinitionRegistry that is embedded in the supplied ParserContext.
     * @param element the element that is to be parsed into one or more BeanDefinitions
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the primary BeanDefinition (can be null as explained above)
     */
    BeanDefinition parse(Element element, ParserContext parserContext);
    
    /**
     * Parse the specified Node and decorate the supplied BeanDefinitionHolder, returning the decorated definition.
     * @param node the source element or attribute that is to be parsed
     * @param definition the current bean definition
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the decorated definition (to be registered in the BeanFactory), or simply the original bean definition if no decoration is required
     */
    BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext);
}

/**
 * Support class for implementing custom NamespaceHandlers.
 */
abstract class NamespaceHandlerSupport implements NamespaceHandler {
    /**
     * Parses the supplied Element by delegating to the BeanDefinitionParser that is registered for that Element.
     * @param element the element that is to be parsed into one or more BeanDefinitions
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the primary BeanDefinition resulting from the parsing of the supplied Element
     */
    public BeanDefinition parse(Element element, ParserContext parserContext);
    
    /**
     * Decorates the supplied Node by delegating to the BeanDefinitionDecorator that is registered to handle that Node.
     * @param node the source element or attribute that is to be parsed
     * @param definition the current bean definition
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the decorated definition
     */
    public BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext);
    
    /**
     * Subclasses can call this to register the supplied BeanDefinitionParser to handle the specified element.
     * @param elementName the name of the element that the parser handles
     * @param parser the parser instance
     */
    protected final void registerBeanDefinitionParser(String elementName, BeanDefinitionParser parser);
    
    /**
     * Subclasses can call this to register the supplied BeanDefinitionDecorator to handle the specified element.
     * @param elementName the name of the element that the decorator handles
     * @param decorator the decorator instance
     */
    protected final void registerBeanDefinitionDecorator(String elementName, BeanDefinitionDecorator decorator);
    
    /**
     * Subclasses can call this to register the supplied BeanDefinitionDecorator to handle the specified attribute.
     * @param attrName the name of the attribute that the decorator handles
     * @param decorator the decorator instance
     */
    protected final void registerBeanDefinitionDecoratorForAttribute(String attrName, BeanDefinitionDecorator decorator);
}

/**
 * Interface used by the DefaultBeanDefinitionDocumentReader to locate a NamespaceHandler implementation for a particular namespace URI.
 */
interface NamespaceHandlerResolver {
    /**
     * Resolve the namespace URI and return the located NamespaceHandler implementation.
     * @param namespaceUri the relevant namespace URI
     * @return the located NamespaceHandler (may be null)
     */
    NamespaceHandler resolve(String namespaceUri);
}

/**
 * Default implementation of the NamespaceHandlerResolver interface.
 */
class DefaultNamespaceHandlerResolver implements NamespaceHandlerResolver {
    /** The location to look for the mapping files. Can be present in multiple JAR files. */
    public static final String DEFAULT_HANDLER_MAPPINGS_LOCATION = "META-INF/spring.handlers";
    
    /**
     * Create a new DefaultNamespaceHandlerResolver using the default mapping file location.
     */
    public DefaultNamespaceHandlerResolver();
    
    /**
     * Create a new DefaultNamespaceHandlerResolver using the default mapping file location.
     * @param classLoader the ClassLoader instance used to load mapping resources (may be null, in which case the thread context ClassLoader will be used)
     */
    public DefaultNamespaceHandlerResolver(ClassLoader classLoader);
    
    /**
     * Create a new DefaultNamespaceHandlerResolver using the supplied mapping file location.
     * @param classLoader the ClassLoader instance used to load mapping resources (may be null, in which case the thread context ClassLoader will be used)
     * @param handlerMappingsLocation the mapping file location
     */
    public DefaultNamespaceHandlerResolver(ClassLoader classLoader, String handlerMappingsLocation);
    
    /**
     * Locate the NamespaceHandler for the supplied namespace URI from the configured mappings.
     * @param namespaceUri the relevant namespace URI
     * @return the located NamespaceHandler; returns null if no NamespaceHandler could be found for the given namespace URI
     */
    public NamespaceHandler resolve(String namespaceUri);
}

Bean Definition Parser Framework

Framework for creating custom bean definition parsers for XML configuration.

/**
 * Interface used by the BeanDefinitionParserDelegate to handle custom, top-level (directly under beans) tags.
 */
interface BeanDefinitionParser {
    /**
     * Parse the specified Element and register the resulting BeanDefinition(s) with the ParserContext.getBeanDefinitionRegistry().
     * @param element the element that is to be parsed into one or more BeanDefinitions
     * @param parserContext the object encapsulating the current state of the parsing process; provides access to a BeanDefinitionRegistry
     * @return the primary BeanDefinition resulting from the parsing of the supplied Element (can be null)
     */
    BeanDefinition parse(Element element, ParserContext parserContext);
}

/**
 * Interface used by the BeanDefinitionParserDelegate to handle custom, nested (directly under a bean) tags.
 */
interface BeanDefinitionDecorator {
    /**
     * Parse the specified Node (either an Element or an Attribute) and decorate the supplied BeanDefinitionHolder, returning the decorated definition.
     * @param node the source element or attribute that is to be parsed
     * @param definition the current bean definition
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the decorated definition (to be registered with the BeanFactory), or simply the original bean definition if no decoration is required
     */
    BeanDefinitionHolder decorate(Node node, BeanDefinitionHolder definition, ParserContext parserContext);
}

/**
 * Convenient base class for BeanDefinitionParsers that need to parse and define just a single BeanDefinition.
 */
abstract class AbstractSingleBeanDefinitionParser implements BeanDefinitionParser {
    /**
     * Creates a BeanDefinitionBuilder instance for the bean Class and passes it to the doParse strategy method.
     * @param element the element that is to be parsed into a single BeanDefinition
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the BeanDefinition resulting from the parsing of the supplied Element
     */
    public final BeanDefinition parse(Element element, ParserContext parserContext);
    
    /**
     * Determine the bean class corresponding to the supplied Element.
     * @param element the Element that is being parsed
     * @return the Class of the bean that is being defined via parsing the supplied Element (must not be null)
     */
    protected abstract Class<?> getBeanClass(Element element);
    
    /**
     * Parse the supplied Element and populate the supplied BeanDefinitionBuilder as required.
     * @param element the XML element being parsed
     * @param parserContext the object encapsulating the current state of the parsing process
     * @param builder used to define the BeanDefinition
     */
    protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder);
    
    /**
     * Parse the supplied Element and populate the supplied BeanDefinitionBuilder as required.
     * @param element the XML element being parsed
     * @param builder used to define the BeanDefinition
     */
    protected void doParse(Element element, BeanDefinitionBuilder builder);
    
    /**
     * Resolve the ID for the supplied BeanDefinition.
     * @param element the element that the bean definition has been built from
     * @param definition the bean definition to be registered
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the resolved id
     * @throws BeanDefinitionStoreException if no unique name can be generated for the given bean definition
     */
    protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException;
    
    /**
     * Extract a bean name from the supplied Element.
     * @param element the element that the bean definition has been built from
     * @return the extracted bean name
     */
    protected String extractBeanName(Element element);
    
    /**
     * Should an ID be generated instead of read from the passed in Element?
     * @param element the element that the bean definition has been built from
     * @return true if an ID should be generated
     */
    protected boolean shouldGenerateId();
    
    /**
     * Should an ID be generated instead even if the passed in Element specifies an "id" attribute explicitly?
     * @param element the element that the bean definition has been built from
     * @return true if an ID should be generated regardless
     */
    protected boolean shouldGenerateIdAsFallback();
}

/**
 * Abstract BeanDefinitionParser implementation providing a number of convenience methods and a template method that subclasses must override to provide the actual parsing logic.
 */
abstract class AbstractBeanDefinitionParser implements BeanDefinitionParser {
    /** Constant for the "id" attribute. */
    public static final String ID_ATTRIBUTE = "id";
    /** Constant for the "name" attribute. */
    public static final String NAME_ATTRIBUTE = "name";
    
    /**
     * Central template method to actually parse the supplied Element into one or more BeanDefinitions.
     * @param element the element that is to be parsed into one or more BeanDefinitions
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the primary BeanDefinition resulting from the parsing of the supplied Element
     */
    public final BeanDefinition parse(Element element, ParserContext parserContext);
    
    /**
     * Parse the specified Element and register any resulting BeanDefinitions with the BeanDefinitionRegistry that is embedded in the supplied ParserContext.
     * @param element the element that is to be parsed into one or more BeanDefinitions
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the primary BeanDefinition resulting from the parsing of the supplied Element (can be null)
     */
    protected abstract AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext);
    
    /**
     * Resolve the ID for the supplied BeanDefinition.
     * @param element the element that the bean definition has been built from
     * @param definition the bean definition to be registered
     * @param parserContext the object encapsulating the current state of the parsing process
     * @return the resolved id
     * @throws BeanDefinitionStoreException if no unique name can be generated for the given bean definition
     */
    protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException;
    
    /**
     * Should an ID be generated instead of read from the passed in Element?
     * @param element the element that the bean definition has been built from
     * @return true if an ID should be generated instead of using element's "id" attribute value
     */
    protected boolean shouldGenerateId();
    
    /**
     * Should an ID be generated instead if the passed in Element does not specify an "id" attribute explicitly?
     * @param element the element that the bean definition has been built from
     * @return true if an ID should be generated if no explicit id specified
     */
    protected boolean shouldGenerateIdAsFallback();
    
    /**
     * Controls whether this parser is supposed to fire a BeanComponentDefinition event after parsing the bean definition.
     * @return true in order to fire a component registration event after parsing the bean definition; false to suppress the registration event
     */
    protected boolean shouldFireEvents();
    
    /**
     * Hook method called after the primary parsing of an Element but before the BeanDefinition has been decorated.
     * @param beanDefinition the parsed (and possibly merged) bean definition being built
     * @param element the element that was the source of the bean definition's metadata
     * @param parserContext the object encapsulating the current state of the parsing process
     */
    protected void postProcessComponentDefinition(AbstractBeanDefinition beanDefinition, Element element, ParserContext parserContext);
}

Usage Examples:

import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

// Basic XML configuration loading
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);

// Load bean definitions from classpath
Resource resource = new ClassPathResource("applicationContext.xml");
int beanCount = reader.loadBeanDefinitions(resource);

// Configure validation mode
reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD);
reader.setNamespaceAware(true);

// Load multiple configuration files
reader.loadBeanDefinitions(
    new ClassPathResource("beans.xml"),
    new ClassPathResource("services.xml"),  
    new ClassPathResource("repositories.xml")
);

// Get configured beans
MyService service = factory.getBean("myService", MyService.class);

Example XML configuration file (applicationContext.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Simple bean definition -->
    <bean id="dataSource" class="com.example.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
        <property name="username" value="user"/>
        <property name="password" value="password"/>
    </bean>

    <!-- Bean with constructor arguments -->
    <bean id="userService" class="com.example.UserService">
        <constructor-arg ref="userRepository"/>
        <constructor-arg value="30"/>
    </bean>

    <!-- Bean with factory method -->
    <bean id="messageFactory" class="com.example.MessageFactory" 
          factory-method="createInstance"/>

    <!-- Bean with init and destroy methods -->
    <bean id="connectionPool" class="com.example.ConnectionPool"
          init-method="initialize" destroy-method="cleanup">
        <property name="maxConnections" value="100"/>
    </bean>

    <!-- Prototype scope bean -->
    <bean id="shoppingCart" class="com.example.ShoppingCart" scope="prototype"/>

    <!-- Lazy initialization -->
    <bean id="expensiveResource" class="com.example.ExpensiveResource" 
          lazy-init="true"/>

    <!-- Bean with depends-on -->
    <bean id="cacheManager" class="com.example.CacheManager" 
          depends-on="dataSource,connectionPool"/>

    <!-- Collection properties -->
    <bean id="emailService" class="com.example.EmailService">
        <property name="templates">
            <map>
                <entry key="welcome" value="templates/welcome.html"/>
                <entry key="goodbye" value="templates/goodbye.html"/>
            </map>
        </property>
        <property name="recipients">
            <list>
                <value>admin@example.com</value>
                <value>support@example.com</value>
            </list>
        </property>
    </bean>

    <!-- Enable annotation-based configuration -->
    <context:annotation-config/>
    
    <!-- Component scanning -->
    <context:component-scan base-package="com.example.services"/>

</beans>

Entity Resolver Support

Support for resolving XML entities, DTDs, and schemas during XML parsing.

/**
 * EntityResolver implementation that delegates to a BeansDtdResolver and a PluggableSchemaResolver for DTDs and XML schemas, respectively.
 */
class DelegatingEntityResolver implements EntityResolver {
    /** Suffix for DTD files. */
    public static final String DTD_SUFFIX = ".dtd";
    /** Suffix for schema definition files. */
    public static final String XSD_SUFFIX = ".xsd";
    
    /**
     * Create a new DelegatingEntityResolver that delegates to a default BeansDtdResolver and a default PluggableSchemaResolver.
     * @param classLoader the ClassLoader to use for loading (can be null to use the default ClassLoader)
     */
    public DelegatingEntityResolver(ClassLoader classLoader);
    
    /**
     * Create a new DelegatingEntityResolver that delegates to the given EntityResolvers.
     * @param dtdResolver the EntityResolver to use for DTDs
     * @param schemaResolver the EntityResolver to use for XML schemas
     */
    public DelegatingEntityResolver(EntityResolver dtdResolver, EntityResolver schemaResolver);
    
    /**
     * Resolve the entity: for DTDs, delegate to the dtdResolver; for schemas, delegate to the schemaResolver.
     * @param publicId the public identifier of the external entity being referenced, or null if none was supplied
     * @param systemId the system identifier of the external entity being referenced
     * @return an InputSource object describing the new input source, or null to request that the parser open a regular URI connection to the system identifier
     * @throws SAXException any SAX exception, possibly wrapping another exception
     * @throws IOException a Java-specific IO exception, possibly the result of creating a new InputStream or Reader for the InputSource
     */
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException;
}

/**
 * EntityResolver implementation for the Spring beans DTD, to load the DTD from the Spring class path (or JAR file).
 */
class BeansDtdResolver implements EntityResolver {
    private static final String DTD_EXTENSION = ".dtd";
    private static final String DTD_NAME = "spring-beans";
    
    /**
     * Resolve the entity: for the beans DTD, return a cached InputSource object; otherwise, return null.
     * @param publicId the public identifier of the external entity being referenced, or null if none was supplied
     * @param systemId the system identifier of the external entity being referenced
     * @return an InputSource object describing the new input source, or null to request that the parser open a regular URI connection to the system identifier
     * @throws IOException if the DTD cannot be loaded
     */
    public InputSource resolveEntity(String publicId, String systemId) throws IOException;
}

/**
 * EntityResolver implementation that attempts to resolve schema URLs into local classpath resources using a set of mappings files.
 */
class PluggableSchemaResolver implements EntityResolver {
    /** The location of the mapping files. */
    public static final String DEFAULT_SCHEMA_MAPPINGS_LOCATION = "META-INF/spring.schemas";
    
    /**
     * Create a new PluggableSchemaResolver that will attempt to resolve schema URL into local classpath resources using the default set of mappings.
     * @param classLoader the ClassLoader to use for loading (can be null to use the default ClassLoader)
     */
    public PluggableSchemaResolver(ClassLoader classLoader);
    
    /**
     * Create a new PluggableSchemaResolver using the supplied ClassLoader and schema mappings location.
     * @param classLoader the ClassLoader to use for loading (can be null to use the default ClassLoader)
     * @param schemaMappingsLocation the location of the file that defines schema mappings (must not be null)
     */
    public PluggableSchemaResolver(ClassLoader classLoader, String schemaMappingsLocation);
    
    /**
     * Resolve the entity: for schema files, attempt to find a mapping in the mappings file and return a corresponding Resource from the classpath.
     * @param publicId the public identifier of the external entity being referenced, or null if none was supplied
     * @param systemId the system identifier of the external entity being referenced
     * @return an InputSource object describing the new input source, or null to request that the parser open a regular URI connection to the system identifier
     * @throws IOException if the schema cannot be loaded
     */
    public InputSource resolveEntity(String publicId, String systemId) throws IOException;
}

Install with Tessl CLI

npx tessl i tessl/maven-org-springframework--spring-beans

docs

annotation-config.md

aot-support.md

bean-definition.md

bean-factory.md

index.md

property-access.md

xml-config.md

tile.json