Spring Schema Customization

Source: Internet
Author: User

Today I looked at the distributed service framework of the book, so it mentions the spring schema of the custom, so to simply understand a bit

Reference resources: Spring Schema extension: http://www.yihaomen.com/article/java/438.htm

Schema Definition: http://www.w3school.com.cn/schema/schema_schema.asp

Spring Schema extension: http://blog.csdn.net/cutesource/article/details/5864562

Spring schema related fields meaning: http://luyuanliang.iteye.com/blog/2154805

When using the distributed services framework, it is often seen that this is used:

interface= "Com.unj.dubbotest.provider.DemoService" ref= "Demoservice"/>  

In many cases, we need to provide configurable support for the system, which can be configured directly based on spring's standard beans, but when the configuration is more complex or requires more rich control,

would seem very clumsy. The general approach is to use the original ecological way to parse the well-defined XML file, and then into the configuration object, which can certainly solve all problems, but the implementation is more cumbersome,

In particular, when the configuration is very complex, parsing is a burden that has to be considered. Spring provides support for extensible schemas, which is a good compromise for completing a custom

Configuration typically requires the following steps:

    • Design Configuration Properties and JavaBean
    • Writing an XSD file
    • Write Namespacehandler and Beandefinitionparser to complete the parsing work
    • Write Spring.handlers and Spring.schemas all parts in tandem
    • Apply in Bean file

1. Setting Configuration Properties

 PackageCom.springwork.xml; Public classpeople {PrivateString name; Private intAge ; PrivateString ID;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }        }

2. Writing an XSD file

<?xml version= "1.0" encoding= "UTF-8"?> <Xsd:schema xmlns= "Http://www.yihaomen.com/schema/people"xmlns:xsd= "Http://www.w3.org/2001/XMLSchema"Xmlns:beans= "Http://www.springframework.org/schema/beans"targetnamespace= "Http://www.yihaomen.com/schema/people"elementFormDefault= "Qualified"attributeFormDefault= "Unqualified" > <xsd:ImportNamespace= "Http://www.springframework.org/schema/beans"/> <xsd:element name= "People" > <xsd:   complextype> <xsd:complexContent> <xsd:extension base= "Beans:identifiedtype" > The composite element is based on a composite element, then adds some elements, the specific explanation looks http://www.w3school.com.cn/schema/schema_complex.asp; <xsd:attri                  Bute name= "name" type= "xsd:string"/> <xsd:attribute name= "age" type= "Xsd:int"/> </xsd:extension> </xsd:complexContent> </xsd:complexType> </xsd:ele Ment> </xsd:schema>

3, write Namespacehandler and Beandefinitionparser complete parsing work

 Package Com.springwork.xml; Import Org.springframework.beans.factory.xml.NamespaceHandlerSupport;    Public class extends Namespacehandlersupport {      publicvoid  init () {          Registerbeandefinitionparser (new  peoplebeandefinitionparser ());      }  }  
 PackageCom.springwork.xml;ImportOrg.springframework.beans.factory.support.BeanDefinitionBuilder; ImportOrg.springframework.beans.factory.xml.AbstractSingleBeanDefinitionParser; Importorg.springframework.util.StringUtils; Importorg.w3c.dom.Element;  Public classPeoplebeandefinitionparserextendsAbstractsinglebeandefinitionparser {protectedClass Getbeanclass (element Element) {returnPeople.class; }      protected voidDoparse (element element, Beandefinitionbuilder Bean) {String name= Element.getattribute ("name"); String Age= Element.getattribute ("Age"); String ID= Element.getattribute ("id"); if(Stringutils.hastext (id)) {bean.addpropertyvalue ("id", id); }          if(Stringutils.hastext (name)) {Bean.addpropertyvalue ("Name", name); }          if(Stringutils.hastext (age)) {Bean.addpropertyvalue ("Age", integer.valueof (age)); }      }  }  

4, write spring.handlers and Spring.schemas all parts in series, the file is located under Src/meta-inf

Http\://www.yihaomen.com/schema/people=com.springwork.xml.mynamespacehandler

  

Http\://www.yihaomen.com/schema/people.xsd=com/springwork/xml/people.xsd

5. Apply in Bean file

Package just the project as a jar, create a new project, and import the jar. Writing a spring configuration file

 <?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "Http://www.springframework.org/schema/beans" Span style= "color: #000000;" > Xmlns:xsi  = "Http://www.w3.org/2001/XMLSchema-instance"  Xmlns:comtest= "Http://www.yihaomen.com/schema/people" //and Spring.handlers first configured connection xsi: schemalocation  = "Http://  Www.springframework.org/schema/beans  http:// Www.springframework.org/schema/beans/spring-beans-2.5.xsd  http://. Span style= "color: #008000;" >www.yihaomen.com/schema/people  http:// Www.yihaomen.com/schema/people.xsd   <comtest:people id=" Cutesource "Name=" one Gate "age="/> </beans> 

6. Test procedure

ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;Importcom.springwork.xml.People; Public classTest { Public Static voidMain (string[] args) {Classpathxmlapplicationcontext ctx=NewClasspathxmlapplicationcontext ("Classpath:/config/application.xml"); People p= (people) Ctx.getbean ("Cutesource");        System.out.println (P.getid ());        System.out.println (P.getname ());    System.out.println (P.getage ()); }}

Extension: xmlns and xsi:schemalocation implication in ApplicationContext

xmlns is an abbreviation for XML namespaces, which is a namespace for XML (a subset of the standard generic markup language). As shown in "dog", the conflict can be resolved by customizing the namespace in situations where a naming conflict is likely to occur.

schemalocation

The SchemaLocation property is used to reference (schema) schema documents, and the parser can use this document to validate XML instance documents when needed. Its value (URI) is a paired occurrence, the first value represents the namespace,

The second value represents the specific location of the schema document that describes the namespace, separated by a space between the two values. Of course, if necessary, you can assign multiple such value pairs to the SchemaLocation property. As shown in.
As can be seen, the configuration is two URL address, in the case of not connected to the network, or the URL is not a real situation, can also be loaded, because there are two configuration files under Meta-inf.

Read local information by mapping. As shown in.

The first value represents a namespace, and the corresponding file is Spring.handlers, which tells spring which class to use for parsing. the second value represents the specific location of the schema document that describes the namespace

about the configuration example diagram: Cat mapping :

Spring Schema 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.