Sunday, March 20, 2011

Namespaces in spring

In earlier versions in spring , spring config relied on the DTD based validation, but from version 2.0, xsd based schemas were introduced. Also we can create our custom schemas and use that in the config file of Spring.

Default Namespace

We use beans namespace as the defualt one. So the tags like beans etc appear from this namespace.

<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-3.0.xsd"
>


Why So many namespaces ?


Since in spring any resource is configured as a bean in the xml file, whether it is a Datasource or JNDI resource or user defined beans. Sometimes it leads to confuse, since the xml file is less verbose.


With namespaces, it becomes easy to identify what type of bean have we configured in the xml file.


Example :


public class SomeBean {

private Properties adminEmails;
//some getters and setters
public void setAdminEmails(Properties adminEmails) {
this.adminEmails = adminEmails;
}

public Properties getAdminEmails() {
return adminEmails;
}
}


Now describing the bean in config file can be done by old-style or newer style.


Old-Style Configuration


<bean id="serviceClass" class="com.xxxx.SomeServiceClass">
<property name="adminEmails" ref="adminProperties">
</bean>

<!-- Old style configuration exposing the actual bean class -->
<bean id="adminEmails" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath:ex7/admin.properties" />
</bean>


New-Style Configuration


<bean id="serviceClass" class="com.xxxx.SomeServiceClass">
<property name="adminEmails" ref="adminProperties">
</bean>

<!-- Now simply refer to the admin mails by new style: -->
<util:properties id="adminEmails" location="classpath:com/xxxx/admin.properties" />


Using the P namespace

No comments:

Post a Comment

Chitika