Thursday, 12 November 2015

Understanding p-namespace and c-namespace in Spring


Background

 In one of the previous post on Spring Dependency Injection we saw how beans are created. We also saw c namespace and how to use it.

  1. For values as dependency (like simple String) you can do <property name="brand" value="MRF"/> or <property name="bat" ref="myBat"/>
  2. Instead of using property tag you can also use p namespace - <bean id="cricket" class="Cricket" p:brand="MRF" p:bat-ref="myBat" />  (don't forget to add the namespace)
  3. Also note p namespace does not have any schema reference. 

Entire Spring configuration bean looks like -

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:p="http://www.springframework.org/schema/p"
  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">

  <bean id="cricket" class="com.osfg.Cricket" p:brand="MRF" p:bat-ref="myBat" />

</beans>


In this post we will see what c name space is and how to use it.

Spring 3.1 Constructor Namespace  

As you already know by now you can do dependency injection by setters or by constructor - setter injection and constructor injection.

Let's see a simple  example of constructor based dependency injection.

 <?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">

  <bean id="cricket" class="com.osfg.Cricket">
    <constructor-arg value="MRF"/>
    <constructor-arg ref="myBat"/>
  </bean>

</beans>

NOTE : The <constructor-arg> tag could take type and index to reduce ambiguity, but not name.

You can simplify above xml using c namespace

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:c="http://www.springframework.org/schema/c"
  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">

  <bean id="cricket" class="com.osfg.Cricket"
    c:brand="MRF"
    c:ref-bat="myBat"/>

</beans>

NOTE : Both the “p” ad “c” namespaces do not have a schema reference in the XML header.

Related Links

No comments:

Post a comment

t> UA-39527780-1 back to top