Home  >  Spring

Spring p-namespace Example

By Arvind Rai, November 05, 2021
In Spring XML, p-namespace is the XML shortcut for <property> tag to inject bean dependency. The p-namespace replaces <property> tag in XML configuration. It is easier and clear to use and increases readability of XML configuration.
Suppose we have <bean> definition in XML as follows.
<bean id="comp" class="com.concretepage.bean.Company">
	<property name="name" value="ABCD Ltd"/>
	<property name="location" value="India"/>
</bean>  
We can change <property> tag using p-namespace as follows.
<bean id="comp" class="com.concretepage.bean.Company" p:name="ABCD Ltd" p:location="India"/> 





Using p-namespace

Find the XML file with p-namespace.
app-conf.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">
      
      <bean id="comp" class="com.concretepage.bean.Company" p:name="ABCD Ltd" p:location="India"/>
      <bean id="emp" class="com.concretepage.bean.Employee" p:empName="Ram Jethmalani" p:company-ref="comp"/>
</beans> 
Find the bean classes used in the example.
Company.java
package com.concretepage.bean;
public class Company {
	private String name;
	private String location;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
} 
Employee.java
package com.concretepage.bean;
public class Employee {
	private String empName;
	private Company company;
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public Company getCompany() {
		return company;
	}
	public void setCompany(Company company) {
		this.company = company;
	}
} 
Run Application.
SpringDemo.java
package com.concretepage;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.concretepage.bean.Employee;
public class SpringDemo {
	public static void main(String[] args) {
	    AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-conf.xml");
	    Employee employee=(Employee)context.getBean("emp");
	    System.out.println(employee.getEmpName());	     
	    System.out.println(employee.getCompany().getName());		
	    context.close();
	}
} 
Find the output.
Ram Jethmalani
ABCD Ltd 
In the same way, for constructor-arg tag, Spring provides c-namespace shortcut. Find the link.

Reference

XML Shortcut with the p-namespace

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI











©2022 concretepage.com | Privacy Policy | Contact Us