Spring Inject Properites with Example

Spring Inject Properites with Example

  • In our Spring Application any Spring Bean contains java.util.properties type properties,Then Spring Container will use The <props> tag to inject the Set Spring Bean.
  • To do This in applicationContext.xml under the <property> tag we need to use <props> tag and under the props we have to use <prop> and <key> attribute.

Tools Used In This Article

  • Spring 3.2.16
  • Maven 4.0.0
  • JDK 1.7

The Project Structure


Maven Dependencies

Add The Following Dependencies to the pom.xml

  • spring-core
  • spring-context

<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>HibernateHqlSelectDemo</groupId>
<artifactId>HibernateHqlSelectDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>>spring-core</artifactId>
<version>3.2.16.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.16.RELEASE</version>
</dependency>

</dependencies>
</project>

Account.java


package com.testpractice;

import java.util.Map;
import java.util.Properties;

public class Hospital {
private Properties hospitalNames;

public Properties getHospitalNames() {
return hospitalNames;
}



public void setHospitalNames(Properties hospitalNames) {
this.hospitalNames = hospitalNames;
}



public void showAccountList() {
System.out.println(hospitalNames);

}


}


applicationContext.xml


<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<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-2.5.xsd">
<bean id = "hospital" class ="com.testpractice.Hospital">

<property name="hospitalNames">
<props>
<prop key = "1">A</prop>
<prop key = "2">B</prop>
<prop key = "3">C</prop>
<prop key = "4">D</prop>
</props>
</property>
</bean>

</beans>

Test.java


package com.testpractice;


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


public class Test {

/**
* @param args
*/
public static void main(String[] args) {

// TODO Auto-generated method stub
ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
Object object =context.getBean("hospital");
Hospital account = (Hospital)object;

account.showAccountList();


}


}


output


{4=D, 3=C, 2=B, 1=A}

-->