^ Click Here

Saturday, March 3, 2012

Spring p:namespace example

Continuing with what we learnt in the Spring Basic we will move on to other functionality

for now our example would be same as the basic example i.e.

Person.java
IAnimal.java
Dog.java
Cat.java

Now we will see the p:namespace option in the Spring config file config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:p="http://www.springframework.org/schema/p"     <!-- This line is required for p:namespace to work -->
    xmlns:xsi="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-3.0.xsd
         http://www.springframework.org/schema/context         
         http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<bean id="person" class="pkg.Person" p:name="Rahul"> 
    <property name="animal" ref="Dog"/>    
</bean>

<bean id="Dog" class="pkg.Dog" p:name="Doug"/>
<bean id="Cat" class="pkg.Cat" p:name="Jejebel"/>

</beans>

If we run the test now it will print the same "Rahul has a Dog with name Doug"....So as you can see the third line initializes the p namespace function through which we get rid of extra property tag in .xml which made the file heavy.
as for p namespace does the same thing which property tag does, it passes the value to the setter method and it's more readable.

To make it more clear if the Person class has an integer age property, then we can pass avalue through p namespace as p:age="32"

But unfortunately we can't pass reference through p namespace. Hence still where we need to pass the reference we are passing other bean we still have to go with property tag.

Do we have anything where we can pass the reference to other bean without property tag?
The answer fortunately is "Yes" however that's a totally unique functionality and hence much more important than p namespace, It's called "Autowiring"

No comments:

Post a Comment