Monday, 27 February 2017

Spring: Inject Properties instance

By using <props> element, you can inject java.util.Properties instance.
public class Countries {
 private Properties countryCapitals;

 .....
 .....
}


Following snippet inject countryCapitals to Countries instance.
 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="countryCapitals">
   <props>
    <prop key="Iceland">Reykjavik</prop>
    <prop key="India">New Delhi</prop>
    <prop key="Indonesia">Jakarta</prop>
    <prop key="Iran">Tehran</prop>
    <prop key="Iraq">Baghdad</prop>
    <prop key="Ireland">Dublin</prop>
    <prop key="Israel">Jerusalem</prop>
    <prop key="Italy">Rome</prop>
   </props>
  </property>
 </bean>

Following is the complete working application.


Countries.java
package com.sample.pojo;

import java.util.Properties;

public class Countries {
 private Properties countryCapitals;

 public Properties getCountryCapitals() {
  return countryCapitals;
 }

 public void setCountryCapitals(Properties countryCapitals) {
  this.countryCapitals = countryCapitals;
 }

}

myConfiguration.xml
<?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="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="countryCapitals">
   <props>
    <prop key="Iceland">Reykjavik</prop>
    <prop key="India">New Delhi</prop>
    <prop key="Indonesia">Jakarta</prop>
    <prop key="Iran">Tehran</prop>
    <prop key="Iraq">Baghdad</prop>
    <prop key="Ireland">Dublin</prop>
    <prop key="Israel">Jerusalem</prop>
    <prop key="Italy">Rome</prop>
   </props>
  </property>
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import java.util.Properties;

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

import com.sample.pojo.Countries;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });
  
  Countries countries = context.getBean("demoCountryCapitals", Countries.class);
  
  Properties props = countries.getCountryCapitals();
  
  for(Object country: props.keySet()){
   System.out.println(country + " " + props.getProperty((String) country));
  }
  
  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
Iceland Reykjavik
Iran Tehran
Indonesia Jakarta
Israel Jerusalem
Italy Rome
India New Delhi
Ireland Dublin
Iraq Baghdad



Previous                                                 Next                                                 Home

No comments:

Post a Comment