Spring Source Learning: XML configuration file label customization

Source: Internet
Author: User

The spring framework, starting with version 2.0, provides schema-style XML extension mechanisms that allow developers to extend the most basic spring configuration files (typically spring.xml under Classpath). Imagine if we add a custom label directly to the Spring.xml <mytag id= "Aty" ></MATAG> what happens? The spring framework starts with an error because spring does not recognize our custom & Lt;mytag>, so the checksum of Spring.xml fails, and the end result is that the framework does not start. Is there a way to let spring know and load parse our custom <mytag>? This is the XML extensibility mechanism provided by spring. We can add our own tags to the spring.xml, and then spring will help us parse and incorporate our own management, which means we have expanded the functionality of spring.

Now let's see how this can be accomplished by referencing the extensible-xml.html in the spring Help documentation. We know that if you need to configure a data source in Spring.xml, you need to configure the following:

<BeanId="DataSource"class="Org.apache.commons.dbcp.BasicDataSource" ><property name= " Driverclassname "value=" Com.mysql.jdbc.Driver "/> <property name= "url" value= "Jdbc:mysql://localhost:3309/sampledb"/> << Span class= "title" >property name= "username"  Value= "root"/> <property name= "password" value= " 1234 "/> </BEAN>         

This configuration, while simple, has one drawback: the use of <property> tags is not obvious enough, not as straightforward as element attributes. Now we want to do the following configuration in Spring.xml, we can complete the configuration of the data source.

<id=url=username=password="root"/>    

This approach is straightforward and configuration is not error prone. If spring is able to parse this tag, it takes 4 steps.

1. Provide an XSD file that is responsible for labeling <datasource> verifying XML

<?xml version= "1.0" encoding= "UTF-8"?><Xsd:schemaxmlns="Http://www.aty.com/schema/aty"Xmlns:xsd="Http://www.w3.org/2001/XMLSchema" xmlns:beans="Http://www.springframework.org/schema/beans" Targetnamespace="Http://www.aty.com/schema/aty"elementformdefault="Qualified" attributeformdefault="Unqualified" > <Xsd:importNamespace="Http://www.springframework.org/schema/beans"/> <Xsd:elementName="DataSource" >  <Xsd:complextype>   <Xsd:complexcontent>    <Xsd:extensionBase="Beans:identifiedtype" >     <Xsd:attributeName="url"Type="Xsd:string"Use="Required"/>     <Xsd:attributeName="UserName"Type="Xsd:string"Use="Required"/>     <xsd:attribute name= "password" type= "xsd:string"  Use= "required"/>    </xsd:extension>   </xsd:complexcontent>< Span class= "indent" >  </xsd:complextype> </xsd:element></ XSD:SCHEMA>              

2. Define a Beandefinitionparser responsible for parsing the XML and putting the necessary information into spring

Package net.aty.custom.define;Import Net.aty.custom.cfg.DataSourceInfo;Import org.springframework.beans.factory.config.BeanDefinition;Import Org.springframework.beans.factory.config.BeanDefinitionHolder;Import Org.springframework.beans.factory.support.BeanDefinitionReaderUtils;Import org.springframework.beans.factory.support.RootBeanDefinition;Import Org.springframework.beans.factory.xml.BeanDefinitionParser;Import Org.springframework.beans.factory.xml.ParserContext;Import org.w3c.dom.Element;PublicClassDatasourcebeandefinitionparserImplementsbeandefinitionparser{ Public Beandefinition Parse (element element, ParserContext context){ Rootbeandefinition def =New Rootbeandefinition ();  Set Bean Class Def.setbeanclass (Datasourceinfo.class);  Registration ID Property String id = element.getattribute ("id"); Beandefinitionholder Idholder =New Beandefinitionholder (Def, id); Beandefinitionreaderutils.registerbeandefinition (Idholder,   Context.getregistry ());  Registering properties String URL = element.getattribute ("url"); String userName = Element.getattribute ("UserName"); String Password = Element.getattribute ("Password"); Beandefinitionholder Urlholder =New Beandefinitionholder (Def, url); Beandefinitionholder Usernameholder =New Beandefinitionholder (Def,   UserName); Beandefinitionholder Passwordholder =New Beandefinitionholder (Def,   password); Beandefinitionreaderutils.registerbeandefinition (Urlholder,   Context.getregistry ()); Beandefinitionreaderutils.registerbeandefinition (Usernameholder,    Context.getregistry ()); Span class= "indent" >  Beandefinitionreaderutils.registerbeandefinition (Passwordholder,    Context.getregistry ());   Def.getpropertyvalues (). Addpropertyvalue ( "url", url); Span class= "indent" >  Def.getpropertyvalues (). Addpropertyvalue ( " UserName ", userName);   Def.getpropertyvalues (). Addpropertyvalue ( " Password ", password);   return def;}}    

The function of the class: set the relevant Beanclass, parse the corresponding XSD file, and register the parsed content in the context, and return a Beandefinition object (beandefinition is the bean definition of spring, Provides operation methods for the Bean section, such as Issingleton (), Islazyinit (), and so on. Note: The id attribute is a default property that can not be described in an XSD file, but it needs to be registered, otherwise the bean defined by the label cannot be obtained through the Getbean method or referenced by another bean.


3, define a Namespacehandler, by the sping framework of the call portal. This is also the portal to our custom XML parsing

package net.aty.custom.define; Import Org.springframework.beans.factory.xml.NamespaceHandlerSupport; public class  Datasourcenamespacehandlersupport extends namespacehandlersupport{< Span class= "indent" >  @Override  public void init ()  {  Registerbeandefinitionparser ( "DataSource",     new datasourcebeandefinitionparser ()); } } 

4. Configuring schema and Handler

Spring is not so smart, it doesn't know where we define the extension tags, who will parse them, and how to parse them. This process tells spring that we know by some configuration files that they are spring.handlers and spring.schemas, which are placed in the Meta-inf directory. Spring.jar's Meta-inf directory also has files with the same name, and their file content is basically similar, and spring will merge them if it finds the two files contained in the Meta-inf folder of the other jar files during execution.

Spring.handlers content is as follows:

Http\://www.aty.com/schema/aty=net.aty.custom.define.  Datasourcenamespacehandlersupport 

Spring.schemas content is as follows:

Http\://www.aty.com/schema/aty.xsd=aty.xsd

My project directory structure is as follows:

The Spring.xml configuration of the test project is as follows:

<?xml version= "1.0" encoding= "UTF-8"?><Beansxmlns="Http://www.springframework.org/schema/beans" Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"  xmlns:aty= "Http://www.aty.com/schema/aty" Span class= "indent" > xsi:schemalocation= "HTTP +/ Www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd Http://www.aty.com/schema/aty http://www.aty.com/ Schema/aty.xsd "> <aty:datasource id=" Mydatasourcce "url=" jdbc:mysql:/ /localhost:3309/demodb "username=" root " Password= "root"/></BEANS>    

The test class code is as follows:

Import Net.aty.custom.cfg.DataSourceInfo;Import Org.springframework.context.support.ClassPathXmlApplicationContext;public class testmain{ Private static Classpathxmlapplicationcontext context = New Classpathxmlapplicationcontext (   "Spring.xml");  public static void Main (string[] args) { datasourceinfo d = (datasourceinfo) context.getbe An ("Mydatasourcce");  System.out.println (d);  }}< /c1>

The project directory structure of the test is as follows:

Spring Source Learning: XML configuration file label customization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.