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;

    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"

        The p-namespace enables you to use the bean element's attribute instead of the property elements

    <bean id="coffeeMachine" class="com.memorynotfound.spring.CoffeeMachine">
        <property name="bean" value="Java"/>
        <property name="amount" value="2.45"/>

    <bean id="pCoffeeMachine" class="com.memorynotfound.spring.CoffeeMachine"
          p:amount="2.19" />


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);

        // get bean with p-namespace
        CoffeeMachine pCoffeeMachine = context.getBean("pCoffeeMachine", CoffeeMachine.class);



The previous code generates the following output:

CoffeeMachine{bean='Java', amount=2.45}
CoffeeMachine{bean='Grocery', amount=2.19}



You may also like...