Quantcast
Channel: Learning the code way
Viewing all articles
Browse latest Browse all 231

The c namespace

$
0
0
With the growth of annotations XML configuration files continue to reduce in size (In some cases they have disappeared). I have never really been a fan of Annotations, especially those that bring in information that was best left outside Java code.
So whenever I come across an XML simplification I get pretty excited (Though I may never get to use it). I had earlier written about the p namespace and how its use reduces the file size. The p namespace was useful when we had getter based wiring. However if you have constructor based wiring than the p namespace is of no real use.
So if wanted to wire a Simple java like this one
publicclass Simple {
publicString value;

public Simple(finalString value) {
this.value = value;
}
}
than the configuration would be :
<bean id="rootBean" class="com.Simple">
<constructor-arg type="java.lang.String" value="Root"/>
</bean>
As seen here, for the constructor injection we use the <constructor-arg> element. This can be now simplified as :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

<bean id="simple" class="com.c_namespace.Simple"c:value="Hello World!"/>
</beans>
The c prefix is followed by the name of the constructor argument. Hence "c:value". This runs fine.
Aug 15, 2013 9:43:26 AM org.springframework.beans.factory.xml.
XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [c_ns.xml]
Hello World!
What if we have a bean as the constructor argument ?Consider the class :
publicclass SimpleDetail {
public Simple simple;

public SimpleDetail(final Simple simple) {
this.simple = simple;
}
}
If we had to define this bean then the configuration would be :
<bean id="simple" class="com.c_namespace.Simple" c:value="Hello World!"/>
<bean id="simpleD" class="com.c_namespace.SimpleDetail"c:simple-ref="simple"/>
It is the <property name>-ref format when dealing with bean as a reference. Just like the p namespace, there is no XSD file defined for c- namespace. It is simply a shortcut method provided for use in the XML configuration

Viewing all articles
Browse latest Browse all 231

Latest Images

Trending Articles



Latest Images