Spring PropertiesFactoryBean

It’s a simple factory for shared Properties instances. It allows for central setup of Properties via the “props” element in XML bean definitions.

Following example demonstrates Spring Properties Factory:

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml




Create Employee Class as following

package com.kruders.bean;

import java.util.Properties;

public class Employee {
	private String name;
	private Properties phone;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public Properties getPhone() {
		return phone;
	public void setPhone(Properties phone) {
		this.phone = phone;

2. Configuration

Create Spring-Bean.xml and write the following code

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="employee" class="com.kruders.bean.Employee">
	   <property name="name" value="Puneet" />
	   <property name="phone">
            <bean class="org.springframework.beans.factory.config.PropertiesFactoryBean">
                <property name="properties">
						<prop key="Home">01123232322</prop>
						<prop key="Mobile">9239232922</prop>

3. Run Program

Create Main.java class that displays the employee details and run it as Java Application

package com.kruders.core;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.kruders.bean.Employee;

public class Main {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Beans.xml");
		Employee employee = (Employee) context.getBean("employee");

		System.out.println("Name " + employee.getName());
		System.out.println("\nPrinting Properties");
		for(String key : employee.getPhone().stringPropertyNames()) {
		    System.out.println(" Number " + employee.getPhone().get(key));

When you run the above example you’ll get an output like:

Name Puneet
Printing Map
City Delhi, Country India

The folder structure of the example is shown below in Figure 44.1

Figure 44.1 Figure 44.1

You can download the source code of this example here.


No comments yet.

Leave a Reply