Dec 24, 2012

Spring Framework - Injecting java properties

In this example we demonstrate how to inject Properties in our application.

The bean configuration file for injecting properties

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  <bean id="databaseConnectionPool" class="com.examples.spring.SQLConnectionPool">
    <property name="properties">
            <prop key="connections">5</prop>
            <prop key="timeout">3600</prop>

The two properties are defined for the SQLConnectionPool class. These properties are injected using the setProperties setter method

package com.examples.spring;

import java.util.Properties;

public class SQLConnectionPool {
 private Properties props;

 public void setProperties(Properties props) {
  this.props = props;

 public String getProperty(String propertyName) {
  return props.getProperty(propertyName);

The unit test program which validates the properties defined for the connection pool class
package com.examples.spring;

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;

 * File:
public class AppTest {

 ApplicationContext ctx = null;

 public void setup() {
  ctx = new ClassPathXmlApplicationContext("beans.xml");

 public void cleanup() {

 public void testPropertyInjection() {
  SQLConnectionPool connectionPool = (SQLConnectionPool) ctx
  Assert.assertEquals(connectionPool.getProperty("connections"), "5");
  Assert.assertEquals(connectionPool.getProperty("timeout"), "3600");

No comments :

Post a Comment