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="http://www.springframework.org/schema/beans"
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">
<bean id="databaseConnectionPool" class="com.examples.spring.SQLConnectionPool">
<property name="properties">
<props>
<prop key="connections">5</prop>
<prop key="timeout">3600</prop>
</props>
</property>
</bean>
</beans>
The two properties are defined for the
SQLConnectionPool class. These properties are injected using the setProperties setter methodpackage 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;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* File: AppTest.java
*/
public class AppTest {
ApplicationContext ctx = null;
@Before
public void setup() {
ctx = new ClassPathXmlApplicationContext("beans.xml");
}
@After
public void cleanup() {
}
@Test
public void testPropertyInjection() {
SQLConnectionPool connectionPool = (SQLConnectionPool) ctx
.getBean("databaseConnectionPool");
Assert.assertEquals(connectionPool.getProperty("connections"), "5");
Assert.assertEquals(connectionPool.getProperty("timeout"), "3600");
}
}
No comments :
Post a Comment