Search This Blog

Friday, 20 September 2013

The c namespace

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
public class Simple {
   public String value;

   public Simple(final String value) {
      this.value = value;
than the configuration would be :
   <bean id="rootBean" class="com.Simple">
      <constructor-arg type="java.lang.String" value="Root" />
As seen here, for the constructor injection we use the <constructor-arg> element. This can be now simplified as :
<beans xmlns=""
   <bean id="simple" class="com.c_namespace.Simple" c:value="Hello World!" />
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 :
public class 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

No comments:

Post a Comment