spring

Spring p-namespace Example

Spring framework provides several namespaces to simplify the xml configuration. In spring, developers can use the p-namespace to inject the setter-based dependency and an alternative to using the <property> tag.

1. Introduction

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
      • Support for Transaction Management
      • Support for interaction with the different databases
      • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
      • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
      • Support for REST style web-services

1.1 Spring P-namespace

In spring, developers use the traditional <property> tag to set the properties of any bean. To avoid this, developers can use the p-namespace to perform the setter-based dependency injection. To use it, developers add a declaration in the spring configuration file i.e.

<?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">
		
. . . . . .
		
</beans>

Benefits of P-namespace

  • Offers compactness and simplicity than the traditional <property> tag
  • Reduces the number of angle brackets in the spring configuration file

Now, open up the Eclipse IDE and let us see how to implement this tag in the spring framework!

2. Spring p-namespace Example

Here is a systematic guide for implementing this tutorial in the spring framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring p-namespace - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring p-namespace - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Spring p-namespace - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring p-namespace - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.core.namespace</groupId>
	<artifactId>SpringPNamespace</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.spring.core.namespace</groupId>
	<artifactId>SpringPNamespace</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>Spring "p" namespace</name>
	<description>A tutorial to demonstrate the "p" namespace in the spring framework</description>
	<dependencies>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>5.1.3.RELEASE</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
	</build>
</project>

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Address bean

We have a simple Address bean with two attributes. We are going to inject values into this bean using the p-namespace tag. Add the following code to the bean definition.

Address.java

package com.spring.model;

public class Address {

	private String city;
	private long zipcode;

	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public long getZipcode() {
		return zipcode;
	}
	public void setZipcode(long zipcode) {
		this.zipcode = zipcode;
	}

	@Override
	public String toString() {
		return "Address [city=" + city + ", zipcode=" + zipcode + "]";
	}
}

3.2.2 Implementation of Employee bean

We have a simple Employee bean with three attributes. We are going to inject values into this bean using the p-namespace tag. Add the following code to the bean definition.

Employee.java

package com.spring.model;

public class Employee {

	private String id;
	private String name;

	// Address is an another bean contains employee's address information.
	private Address address;

	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", address=" + address + "]";
	}
}

3.2.3 Implementation of Utility Class

Add the following code to the implementation class for testing the p-namespace injection.

Demoapp.java

package com.spring.main;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.Employee;

public class Demoapp {

	public static void main(String[] args) {

		// Reading configuration from the spring configuration file.
		ConfigurableApplicationContext   context = new ClassPathXmlApplicationContext("spring-namespace-config.xml");

		Employee myemployee = context.getBean("employeeBean", Employee.class);

		System.out.println(myemployee);

		// Closing the context object.
		context.close();
	}
}

3.3 Bean Configuration file

In the spring xml configuration, we’ll inject the properties of the bean using the p-namespace.

spring-namespace-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"
	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">

	<!-- Old way of specifying the bean properties -->
	<!-- 
		<bean id="addrBean" class="com.spring.model.Address">
			<property name="city" value="Gurugram" />
			<property name="zipcode" value="201301" />
		</bean>

		<bean id="employeeBean" class="com.spring.model.Employee">
			<property name="id" value="1234" />
			<property name="name" value="Daniel" />
			<property name="address" ref="addrBean" />
		</bean>
	-->

	<!-- **New way** | Specifying bean properties by using the spring "p" namespace -->
	<bean id="addrBean" class="com.spring.model.Address"
		p:city="Gurugram" p:zipcode="201301" />

	<bean id="employeeBean" class="com.spring.model.Employee"
		p:id="1234" p:name="Daniel" p:address-ref="addrBean" />
</beans>

4. Run the Application

To execute the application, right click on the Demoapp class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Spring p-namespace - Run the Application
Fig. 5: Run the Application

5. Project Demo

The code shows the following log as the output of this tutorial.

Employee [id=1234, name=Daniel, address=Address [city=Gurugram, zipcode=201301]] 

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of the p-namespace in the spring framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of spring p-namespace for beginners.

Download
You can download the full source code of this example here: SpringPNamespace

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button