加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML Schema-based configuration

发布时间:2020-12-16 06:15:10 所属栏目:百科 来源:网络整理
导读:XML Schema-based configuration 34.1Introduction This appendix details the XML Schema-based configuration introduced in Spring 2.0 and enhanced and extended in Spring 2.5 and 3.0. DTD support? Authoring Spring configuration files using the

XML Schema-based configuration

34.1Introduction

This appendix details the XML Schema-based configuration introduced in Spring 2.0 and enhanced and extended in Spring 2.5 and 3.0.

The central motivation for moving to XML Schema based configuration files was to make Spring XML configuration easier. The'classic'<bean/>-based approach is good,but its generic-nature comes with a price in terms of configuration overhead.

From the Spring IoC containers point-of-view,everythingis a bean. That’s great news for the Spring IoC container,because if everything is a bean then everything can be treated in the exact same fashion. The same,however,is not true from a developer’s point-of-view. The objects defined in a Spring XML configuration file are not all generic,vanilla beans. Usually,each bean requires some degree of specific configuration.

Spring 2.0’s new XML Schema-based configuration addresses this issue. The<bean/>element is still present,and if you wanted to,you could continue to write theexact samestyle of Spring XML configuration using only<bean/>elements. The new XML Schema-based configuration does,make Spring XML configuration files substantially clearer to read. In addition,it allows you to express the intent of a bean definition.

The key thing to remember is that the new custom tags work best for infrastructure or integration beans: for example,AOP,collections,transactions,integration with 3rd-party frameworks such as Mule,etc.,while the existing bean tags are best suited to application-specific beans,such as DAOs,service layer objects,validators,etc.

The examples included below will hopefully convince you that the inclusion of XML Schema support in Spring 2.0 was a good idea. The reception in the community has been encouraging; also,please note the fact that this new configuration mechanism is totally customisable and extensible. This means you can write your own domain-specific configuration tags that would better represent your application’s domain; the process involved in doing so is covered in the appendix entitledChapter35,Extensible XML authoring.

34.2XML Schema-based configuration

34.2.1Referencing the schemas

To switch over from the DTD-style to the new XML Schema-style,you need to make the following change.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
        "http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>

<!-- bean definitions here -->

</beans>

The equivalent file in the XML Schema-style would be…

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    </beans>

The'xsi:schemaLocation'fragment is not actually required,but can be included to reference a local copy of a schema (which can be useful during development).

The above Spring XML configuration fragment is boilerplate that you can copy and paste (!) and then plug<bean/>definitions into like you have always done. However,the entire point of switching over is to take advantage of the new Spring 2.0 XML tags since they make configuration easier. The section entitledSection34.2.2,“the util schema”demonstrates how you can start immediately by using some of the more common utility tags.

The rest of this chapter is devoted to showing examples of the new Spring XML Schema based configuration,with at least one example for every new tag. The format follows a before and after style,with abeforesnippet of XML showing the old (but still 100% legal and supported) style,followed immediately by anafterexample showing the equivalent in the new XML Schema-based style.

34.2.2the util schema

First up is coverage of theutiltags. As the name implies,theutiltags deal with common,utilityconfiguration issues,such as configuring collections,referencing constants,and suchlike.

To use the tags in theutilschema,you need to have the following preamble at the top of your Spring XML configuration file; the text in the snippet below references the correct schema so that the tags in theutilnamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> </beans>

<util:constant/>

Before…

<bean id="..." class="...">
    <property name="isolation">
        "java.sql.Connection.TRANSACTION_SERIALIZABLE"
                "org.springframework.beans.factory.config.FieldRetrievingFactoryBean" />
    </property>
</bean>

The above configuration uses a SpringFactoryBeanimplementation,242)">FieldRetrievingFactoryBean,to set the value of theisolationproperty on a bean to the value of thejava.sql.Connection.TRANSACTION_SERIALIZABLEconstant. This is all well and good,but it is a tad verbose and (unnecessarily) exposes Spring’s internal plumbing to the end user.

The following XML Schema-based version is more concise and clearly expresses the developer’s intent ('inject this constant value'),and it just reads better.

<util:constant static-field="java.sql.Connection.TRANSACTION_SERIALIZABLE"/>
    </bean>
Setting a bean property or constructor arg from a field value

FieldRetrievingFactoryBeanis aFactoryBeanwhich retrieves astaticor non-static field value. It is typically used for retrievingpublicstaticfinalconstants,which may then be used to set a property value or constructor arg for another bean.

Find below an example which shows how astaticfield is exposed,by using thestaticFieldproperty:

"myField"
        "staticField" value=/>
</bean>

There is also a convenience usage form where thestaticfield is specified as the bean name:

"java.sql.Connection.TRANSACTION_SERIALIZABLE"
        />

This does mean that there is no longer any choice in what the bean id is (so any other bean that refers to it will also have to use this longer name),but this form is very concise to define,and very convenient to use as an inner bean since the id doesn’t have to be specified for the bean reference:

</bean>

It is also possible to access a non-static (instance) field of another bean,as described in the API documentation for theFieldRetrievingFactoryBeanclass.

Injecting enum values into beans as either property or constructor arguments is very easy to do in Spring,in that you don’t actually have todoanything or know anything about the Spring internals (or even about classes such as theFieldRetrievingFactoryBean). Let’s look at an example to see how easy injecting an enum value is; consider this JDK 5 enum:

package javax.persistence;

public enum PersistenceContextType {

    TRANSACTION,EXTENDED

}

Now consider a setter of typePersistenceContextType:

package example;

public class Client {

    private PersistenceContextType persistenceContextType;

    void setPersistenceContextType(PersistenceContextType type) {
        this.persistenceContextType = type;
    }

}
  1. and the corresponding bean definition:
"example.Client""persistenceContextType" "TRANSACTION" />
</bean>

This works for classic type-safe emulated enums (on JDK 1.4 and JDK 1.3) as well; Spring will automatically attempt to match the string property value to a constant on the enum class.

<util:property-path/>

Before…

<!-- target bean to be referenced by name -->
"testBean" "org.springframework.beans.TestBean" scope="prototype""age" "10""spouse""org.springframework.beans.TestBean">
            "11"/>
        </bean>
    </bean>

<!-- will result in 10,which is the value of property age of bean testBean -->
"testBean.age" "org.springframework.beans.factory.config.PropertyPathFactoryBean"/>

The above configuration uses a SpringPropertyPathFactoryBean,to create a bean (of typeint) calledtestBean.agethat has a value equal to theageproperty of thetestBeanbean.

After…

<util:property-path "name" path="testBean.age"/>

The value of thepathattribute of the<property-path/>tag follows the formbeanName.beanProperty.

Using <util:property-path/> to set a bean property or constructor-argument

PropertyPathFactoryBeanis aFactoryBeanthat evaluates a property path on a given target object. The target object can be specified directly or via a bean name. This value may then be used in another bean definition as a property value or constructor argument.

Here’s an example where a path is used against another bean,by name:

// target bean to be referenced by name
"person" </bean>

// will result in 11,which is the value of property spouse.age of bean person
"theAge"
        "targetBeanName" "person""propertyPath" "spouse.age"</bean>

In this example,a path is evaluated against an inner bean:

<!-- will result in 12,which is the value of property age of the inner bean -->
"targetObject""12"</property>
    "age"</bean>

There is also a shortcut form,where the bean name is the property path.

age of bean person -->
"person.age"
        />

This form does mean that there is no choice in the name of the bean. Any reference to it will also have to use the same id,which is the path. Of course,if used as an inner bean,there is no need to refer to it at all:

"person.age"
                </bean>

The result type may be specifically set in the actual definition. This is not necessary for most use cases,but can be of use for some. Please see the Javadocs for more info on this feature.

<util:properties/>

Before…

<!-- creates a java.util.Properties instance with values loaded from the supplied location -->
"jdbcConfiguration" "org.springframework.beans.factory.config.PropertiesFactoryBean""location" "classpath:com/foo/jdbc-production.properties"PropertiesFactoryBean,to instantiate ajava.util.Propertiesinstance with values loaded from the suppliedResourcelocation).

After…

<util:properties location=/>

<util:list/>

Before…

<!-- creates a java.util.List instance with values loaded from the supplied sourceList -->
"emails" "org.springframework.beans.factory.config.ListFactoryBean""sourceList"<list>
            <value>pechorin@hero.org</value>
            <value>raskolnikov@slums.org<value>stavrogin@gov.org<value>porfiry@gov.org</value>
        </list>
    ListFactoryBean,to create ajava.util.Listinstance initialized with values taken from the suppliedsourceList.

After…

<!-- creates a java.util.List instance with the supplied values -->
<util:list "emails"</value>
    </value>
</util:list>

You can also explicitly control the exact type ofListthat will be instantiated and populated via the use of thelist-classattribute on the<util:list/>element. For example,if we really need ajava.util.LinkedListto be instantiated,we could use the following configuration:

list-class="java.util.LinkedList"<value>jackshaftoe@vagabond.org<value>eliza@thinkingmanscrumpet.org<value>vanhoek@pirate.org<value>d'Arcachon@nemesis.org</util:list>

If nolist-classattribute is supplied,aListimplementation will be chosen by the container.

<util:map/>

Before…

<!-- creates a java.util.Map instance with values loaded from the supplied sourceMap -->
"org.springframework.beans.factory.config.MapFactoryBean""sourceMap"<map>
            <entry key="pechorin" "pechorin@hero.org"/>
            "raskolnikov" "raskolnikov@slums.org""stavrogin" "stavrogin@gov.org""porfiry" "porfiry@gov.org"</map>
    MapFactoryBean,242)">java.util.Mapinstance initialized with key-value pairs taken from the supplied'sourceMap'.

After…

<!-- creates a java.util.Map instance with the supplied key-value pairs -->
<util:map </util:map>

You can also explicitly control the exact type ofMapthat will be instantiated and populated via the use of the'map-class'attribute on the<util:map/>element. For example,242)">java.util.TreeMapto be instantiated,127)">map-class="java.util.TreeMap"</util:map>

If no'map-class'attribute is supplied,242)">Mapimplementation will be chosen by the container.

<util:set/>

Before…

<!-- creates a java.util.Set instance with values loaded from the supplied sourceSet -->
"org.springframework.beans.factory.config.SetFactoryBean""sourceSet"<set>
            </set>
    SetFactoryBean,242)">java.util.Setinstance initialized with values taken from the supplied'sourceSet'.

After…

<!-- creates a java.util.Set instance with the supplied values -->
<util:set </util:set>

You can also explicitly control the exact type ofSetthat will be instantiated and populated via the use of the'set-class'attribute on the<util:set/>element. For example,242)">java.util.TreeSetto be instantiated,127)">set-class="java.util.TreeSet"</util:set>

If no'set-class'attribute is supplied,242)">Setimplementation will be chosen by the container.

34.2.3the jee schema

Thejeetags deal with Java EE (Java Enterprise Edition)-related configuration issues,such as looking up a JNDI object and defining EJB references.

To use the tags in thejeeschema,you need to have the following preamble at the top of your Spring XML configuration file; the text in the following snippet references the correct schema so that the tags in thejeenamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">  <jee:jndi-lookup/> (simple) 
     

Before…

"dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    "jndiName" "jdbc/MyDataSource"</bean>
"userDao" "com.foo.JdbcUserDao">
    <!-- Spring will do the cast automatically (as usual) -->
    "dataSource" ref="dataSource"/>
</bean>

After…

<jee:jndi-lookup "dataSource" jndi-name="jdbc/MyDataSource"/>

</bean>

<jee:jndi-lookup/> (with single JNDI environment setting)

Before…

"simple" "org.springframework.jndi.JndiObjectFactoryBean""jndiEnvironment"<props>
            <prop "foo">bar</prop>
        </props>
    jndi-name=<jee:environment>foo=bar</jee:environment>
</jee:jndi-lookup>

<jee:jndi-lookup/> (with multiple JNDI environment settings)

Before…

</prop>
            "ping">pong<!-- newline-separated,key-value pairs for the environment (standard Properties format) -->
    <jee:environment>
        foo=bar
        ping=pong
     <jee:jndi-lookup/> (complex) 
     

Before…

"cache" "true""resourceRef" "lookupOnStartup" "false""expectedType" "com.myapp.DefaultFoo""proxyInterface" "com.myapp.Foo""simple"
        "jdbc/MyDataSource"
        cache="true"
        resource-ref=lookup-on-startup="false"
        expected-type="com.myapp.DefaultFoo"
        proxy-interface= <jee:local-slsb/> (simple) 
      
     
    
   

The<jee:local-slsb/>tag configures a reference to an EJB Stateless SessionBean.

Before…

"org.springframework.ejb.access.LocalStatelessSessionProxyFactoryBean""ejb/RentalServiceBean""businessInterface" "com.foo.service.RentalService"<jee:local-slsb "simpleSlsb" "ejb/RentalServiceBean"
        business-interface= <jee:local-slsb/> (complex) 
      
     
    
   
"complexLocalEjb"
        "cacheHome" "lookupHomeOnStartup" "com.foo.service.RentalService"
        cache-home=lookup-home-on-startup=>

<jee:remote-slsb/>

The<jee:remote-slsb/>tag configures a reference to aremoteEJB Stateless SessionBean.

Before…

"complexRemoteEjb"
        "org.springframework.ejb.access.SimpleRemoteStatelessSessionProxyFactoryBean""ejb/MyRemoteBean""homeInterface" "refreshHomeOnConnectFailure" <jee:remote-slsb "ejb/MyRemoteBean"
        home-interface=refresh-home-on-connect-failure=>

34.2.4the lang schema

Thelangtags deal with exposing objects that have been written in a dynamic language such as JRuby or Groovy as beans in the Spring container.

These tags (and the dynamic language support) are comprehensively covered in the chapter entitledChapter29,Dynamic language support. Please do consult that chapter for full details on this support and thelangtags themselves.

In the interest of completeness,to use the tags in thelangschema,242)">langnamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:lang="http://www.springframework.org/schema/lang" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd"> </beans>

34.2.5the jms schema

Thejmstags deal with configuring JMS-related beans such as Spring’sMessageListenerContainers. These tags are detailed in the section of theJMS chapterentitledSection24.7,“JMS Namespace Support”. Please do consult that chapter for full details on this support and thejmstags themselves.

In the interest of completeness,242)">jmsschema,242)">jmsnamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jms="http://www.springframework.org/schema/jms" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms.xsd">  34.2.6the tx (transaction) schema 
    

Thetxtags deal with configuring all of those beans in Spring’s comprehensive support for transactions. These tags are covered in the chapter entitledChapter12,Transaction Management.

You are strongly encouraged to look at the'spring-tx.xsd'file that ships with the Spring distribution. This file is (of course),the XML Schema for Spring’s transaction configuration,and covers all of the various tags in thetxnamespace,including attribute defaults and suchlike. This file is documented inline,and thus the information is not repeated here in the interests of adhering to the DRY (Don’t Repeat Yourself) principle.

In the interest of completeness,242)">txschema,242)">txnamespace are available to you.

"http://www.springframework.org/schema/beans"
        "http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">  Often when using the tags in thetxnamespace you will also be using the tags from theaopnamespace (since the declarative transaction support in Spring is implemented using AOP). The above XML snippet contains the relevant lines needed to reference theaopschema so that the tags in theaopnamespace are available to you.

34.2.7the aop schema

Theaoptags deal with configuring all things AOP in Spring: this includes Spring’s own proxy-based AOP framework and Spring’s integration with the AspectJ AOP framework. These tags are comprehensively covered in the chapter entitledChapter9,Aspect Oriented Programming with Spring.

In the interest of completeness,242)">aopschema,242)">aopnamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">  34.2.8the context schema 
    

Thecontexttags deal withApplicationContextconfiguration that relates to plumbing - that is,not usually beans that are important to an end-user but rather beans that do a lot of grunt work in Spring,such asBeanfactoryPostProcessors. The following snippet references the correct schema so that the tags in thecontextnamespace are available to you.

"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"> contextschema was only introduced in Spring 2.5.

<property-placeholder/>

This element activates the replacement of${...}placeholders,resolved against the specified properties file (as aSpring resource location). This element is a convenience mechanism that sets up aPropertyPlaceholderConfigurerfor you; if you need more control over thePropertyPlaceholderConfigurer,just define one yourself explicitly.

<annotation-config/>

Activates the Spring infrastructure for various annotations to be detected in bean classes: Spring’s@Requiredand@Autowired,as well as JSR 250’s@PostConstruct,@PreDestroyand@Resource(if available),and JPA’s@PersistenceContextand@PersistenceUnit(if available). Alternatively,you can choose to activate the individualBeanPostProcessorsfor those annotations explicitly.

This element doesnotactivate processing of Spring’s@Transactionalannotation. Use the<tx:annotation-driven/>element for that purpose.

<component-scan/>

This element is detailed inSection5.9,“Annotation-based container configuration”.

<load-time-weaver/>

This element is detailed inSection9.8.4,“Load-time weaving with AspectJ in the Spring Framework”.

<spring-configured/>

This element is detailed inSection9.8.1,“Using AspectJ to dependency inject domain objects with Spring”.

<mbean-export/>

This element is detailed inSection25.4.3,“Configuring annotation based MBean export”.

34.2.9the tool schema

Thetooltags are for use when you want to add tooling-specific metadata to your custom configuration elements. This metadata can then be consumed by tools that are aware of this metadata,and the tools can then do pretty much whatever they want with it (validation,etc.).

Thetooltags are not documented in this release of Spring as they are currently undergoing review. If you are a third party tool vendor and you would like to contribute to this review process,then do mail the Spring mailing list. The currently supportedtooltags can be found in the file'spring-tool.xsd'in the'src/org/springframework/beans/factory/xml'directory of the Spring source distribution.

34.2.10the jdbc schema

Thejdbctags allow you to quickly configure an embedded database or initialize an existing data source. These tags are documented inSection14.8,“Embedded database support”andSection14.9,“Initializing a DataSource”respectively.

To use the tags in thejdbcschema,242)">jdbcnamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">  34.2.11the cache schema 
    

Thecachetags can be used to enable support for Spring’s@CacheEvict,242)">@CachePutand@Cachingannotations. It it also supports declarative XML-based caching. SeeSection30.3.6,“Enable caching annotations”andSection30.5,“Declarative XML-based caching”for details.

To use the tags in thecacheschema,242)">cachenamespace are available to you.

"http://www.w3.org/2001/XMLSchema-instance"
    xmlns:jdbc="http://www.springframework.org/schema/cache" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/cache http://www.springframework.org/schema/jdbc/spring-cache.xsd">  34.2.12the beans schema 
     
    
   
  

Last but not least we have the tags in thebeansschema. These are the same tags that have been in Spring since the very dawn of the framework. Examples of the various tags in thebeansschema are not shown here because they are quite comprehensively covered inSection5.4.2,“Dependencies and configuration in detail”(and indeed in that entirechapter).

One thing that is new to the beans tags themselves in Spring 2.0 is the idea of arbitrary bean metadata. In Spring 2.0 it is now possible to add zero or more key / value pairs to<bean/>XML definitions. What,if anything,is done with this extra metadata is totally up to your own custom logic (and so is typically only of use if you are writing your own custom tags as described in the appendix entitledExtensible XML authoring).

Find below an example of the<meta/>tag in the context of a surrounding<bean/>(please note that without any logic to interpret it the metadata is effectively useless as-is).

>

    "foo" "x.y.Foo">
        <meta key="cacheName" value="foo"/>
        "Rick"</bean>

</beans>

In the case of the above example,you would assume that there is some logic that will consume the bean definition and set up some caching infrastructure using the supplied metadata.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!