Spring p-namespace XML Configuration Shortcut
This example shows you how to use the spring p-namespace XML shortcut. The p-namespace is created to simplify the XML configuration. This namespace enables you to use the bean
element’s attributes, instead of <property/>
elements. In this tutorial we’ll have a look at the classical way of describing a bean and the one in which we use the p-namespace.
Simple POJO
We have a simple CoffeeMachine
class with two attributes, bean and amount. Later we are going to inject values into this bean using setter-dependency-injection.
package com.memorynotfound.spring;
public class CoffeeMachine {
private String bean;
private double amount;
public String getBean() {
return bean;
}
public void setBean(String bean) {
this.bean = bean;
}
public double getAmount() {
return amount;
}
public void setAmount(double amount) {
this.amount = amount;
}
@Override
public String toString() {
return "CoffeeMachine{" +
"bean='" + bean + '\'' +
", amount=" + amount +
'}';
}
}
Spring p-namespace XML shortcut
First we create a CoffeeMachine
using the classical way. We inject values using the <property/>
element. Next we create a CoffeeMachine
using the p-namespace. This allows us to use the bean element’s attributes directly.
<?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">
<description>
The p-namespace enables you to use the bean element's attribute instead of the property elements
</description>
<bean id="coffeeMachine" class="com.memorynotfound.spring.CoffeeMachine">
<property name="bean" value="Java"/>
<property name="amount" value="2.45"/>
</bean>
<bean id="pCoffeeMachine" class="com.memorynotfound.spring.CoffeeMachine"
p:bean="Grocery"
p:amount="2.19" />
</beans>
Bootstrap Application
We created two bean definitions earlier. The traditional coffeeMachine bean and the p-namespace pCoffeeMachine bean. We simply print the result to the console to show the output.
package com.memorynotfound.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Run {
public static void main(String... args){
ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"app-config.xml"});
// get bean with property
CoffeeMachine coffeeMachine = context.getBean("coffeeMachine", CoffeeMachine.class);
System.out.println(coffeeMachine);
// get bean with p-namespace
CoffeeMachine pCoffeeMachine = context.getBean("pCoffeeMachine", CoffeeMachine.class);
System.out.println(pCoffeeMachine);
}
}
Demo
The previous code generates the following output:
CoffeeMachine{bean='Java', amount=2.45}
CoffeeMachine{bean='Grocery', amount=2.19}