Wednesday, 15 March 2017

Spring: Collections merging

Spring API provides support to merge collections. You can define a bean such that, the collection of elements of child bean can be inherited form parent bean.

Example
 <bean id="parent" abstract="true" class="com.sample.pojo.Organization">
  <property name="orgEmails">
   <props>
    <prop key="administrator">administrator@example.com</prop>
    <prop key="support">support@example.com</prop>
   </props>
  </property>
 </bean>

 <bean id="child" parent="parent">
  <property name="orgEmails">
   <!-- the merge is specified on the child collection definition -->
   <props merge="true">
    <prop key="sales">sales@example.com</prop>
    <prop key="support">support@example.co.in</prop>
   </props>
  </property>
 </bean>

Notice the use of the merge=true attribute on the <props/> element of the orgEmails property of the child bean definition. When the child bean is resolved and instantiated by the container, the resulting instance has an orgEmails Properties collection that contains the result of the merging of the child’s orgEmails collection with the parent’s orgEmails collection.

The child Properties collection’s value set inherits all property elements from the parent <props/>, and the child’s value for the support value overrides the value in the parent collection.

Following is the complete working application.

Organization.java
package com.sample.pojo;

import java.util.Properties;

public class Organization {
 private Properties orgEmails;

 public Properties getOrgEmails() {
  return orgEmails;
 }

 public void setOrgEmails(Properties orgEmails) {
  this.orgEmails = orgEmails;
 }

}

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="parent" abstract="true" class="com.sample.pojo.Organization">
  <property name="orgEmails">
   <props>
    <prop key="administrator">administrator@example.com</prop>
    <prop key="support">support@example.com</prop>
   </props>
  </property>
 </bean>

 <bean id="child" parent="parent">
  <property name="orgEmails">
   <!-- the merge is specified on the child collection definition -->
   <props merge="true">
    <prop key="sales">sales@example.com</prop>
    <prop key="support">support@example.co.in</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.Organization;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Organization organization = context.getBean("child", Organization.class);

  Properties props = organization.getOrgEmails();
  
  for(Object property: props.keySet()){
   System.out.println(property + " : " + props.get(property));
  }

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
support : support@example.co.in
administrator : administrator@example.com
sales : sales@example.com

In the same way you can apply merging to all supported collecitons like List, Map, Set.

Can I merge Collections of different types?

No, you can’t merge collections of different types. For example, if you try to merger Map collection to List, you will get an exception.



Previous                                                 Next                                                 Home

Spring: Inject map of beans (key and value both are beans)

In my previous post, I explained how to inject map, where key is an integer and value is pointed to a bean. In this post, I am going to explain how to inject a map where key and value are beans.

By using <map>, <entry> elements, key-ref and value-ref attributes, you can inject map of beans.

Example
 <bean id="countryInfo" name="countryInfo" class="com.sample.pojo.Countries">
  <property name="countriesMap">
   <map>
    <entry key-ref="india" value-ref="indiaInfo" />
    <entry key-ref="russia" value-ref="russiaInfo" />
   </map>
  </property>
 </bean>

Following is the complete working application.

Country.java
package com.sample.pojo;

public class Country {
 private String name;
 private String capital;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCapital() {
  return capital;
 }

 public void setCapital(String capital) {
  this.capital = capital;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Country [name=").append(name).append(", capital=").append(capital).append("]");
  return builder.toString();
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((capital == null) ? 0 : capital.hashCode());
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Country other = (Country) obj;
  if (capital == null) {
   if (other.capital != null)
    return false;
  } else if (!capital.equals(other.capital))
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

}

CountryInformation.java
package com.sample.pojo;

public class CountryInformation {
 private String language;
 private String currency;

 public String getLanguage() {
  return language;
 }

 public void setLanguage(String language) {
  this.language = language;
 }

 public String getCurrency() {
  return currency;
 }

 public void setCurrency(String currency) {
  this.currency = currency;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("CountryInformation [language=").append(language).append(", currency=").append(currency)
    .append("]");
  return builder.toString();
 }

}

Countries.java
package com.sample.pojo;

import java.util.Map;

public class Countries {
 private Map<Country, CountryInformation> countriesMap;

 public Map<Country, CountryInformation> getCountriesMap() {
  return countriesMap;
 }

 public void setCountriesMap(Map<Country, CountryInformation> countriesMap) {
  this.countriesMap = countriesMap;
 }

}

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="india" class="com.sample.pojo.Country">
  <property name="name" value="India" />
  <property name="capital" value="New Delhi" />
 </bean>

 <bean id="russia" class="com.sample.pojo.Country">
  <property name="name" value="Russia" />
  <property name="capital" value="Moscow" />
 </bean>

 <bean id="russiaInfo" class="com.sample.pojo.CountryInformation">
  <property name="language" value="Russian" />
  <property name="currency" value="Ruble" />
 </bean>


 <bean id="indiaInfo" class="com.sample.pojo.CountryInformation">
  <property name="language" value="Hindi" />
  <property name="currency" value="Rupee" />
 </bean>

 <bean id="countryInfo" name="countryInfo" class="com.sample.pojo.Countries">
  <property name="countriesMap">
   <map>
    <entry key-ref="india" value-ref="indiaInfo" />
    <entry key-ref="russia" value-ref="russiaInfo" />
   </map>
  </property>
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import java.util.Set;

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

import com.sample.pojo.Countries;
import com.sample.pojo.Country;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Countries countries = context.getBean("countryInfo", Countries.class);

  Set<Country> countrySet = countries.getCountriesMap().keySet();

  for (Country country : countrySet) {
   System.out.println(country + " : " + countries.getCountriesMap().get(country));
  }

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run ‘HelloWorld.java’, you can able to see following output.
Country [name=India, capital=New Delhi] : CountryInformation [language=Hindi, currency=Rupee]
Country [name=Russia, capital=Moscow] : CountryInformation [language=Russian, currency=Ruble]




Previous                                                 Next                                                 Home

Tuesday, 7 March 2017

Spring: Inject map of beans

In my previous post, I explained how to inject Map<String, String>. By using <map>, <entry> elements, value-ref attributes, you can inject map of beans.

Example
 <bean id="countryCodes" name="countryCodes" class="com.sample.pojo.Countries">
  <property name="countriesMap">
   <map>
    <entry key="91" value-ref="india" />
    <entry key="7" value-ref="russia" />
   </map>
  </property>
 </bean>

Following is the complete working application.

Country.java
package com.sample.pojo;

public class Country {
 private String name;
 private String capital;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCapital() {
  return capital;
 }

 public void setCapital(String capital) {
  this.capital = capital;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Country [name=").append(name).append(", capital=").append(capital).append("]");
  return builder.toString();
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((capital == null) ? 0 : capital.hashCode());
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Country other = (Country) obj;
  if (capital == null) {
   if (other.capital != null)
    return false;
  } else if (!capital.equals(other.capital))
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

}

Countries.java
package com.sample.pojo;

import java.util.Map;

public class Countries {
 private Map<Integer, Country> countriesMap;

 public Map<Integer, Country> getCountriesMap() {
  return countriesMap;
 }

 public void setCountriesMap(Map<Integer, Country> countriesMap) {
  this.countriesMap = countriesMap;
 }

}

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="india" class="com.sample.pojo.Country">
  <property name="name" value="India" />
  <property name="capital" value="New Delhi" />
 </bean>

 <bean id="russia" class="com.sample.pojo.Country">
  <property name="name" value="Russia" />
  <property name="capital" value="Moscow" />
 </bean>

 <bean id="countryCodes" name="countryCodes" class="com.sample.pojo.Countries">
  <property name="countriesMap">
   <map>
    <entry key="91" value-ref="india" />
    <entry key="7" value-ref="russia" />
   </map>
  </property>
 </bean>

</beans>

HelloWorld.java

package com.sample.test;

import java.util.Set;

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("countryCodes", Countries.class);

  Set<Integer> countryCodes = countries.getCountriesMap().keySet();

  for (Integer countryCode : countryCodes) {
   System.out.println(countryCode + " : " + countries.getCountriesMap().get(countryCode));
  }

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java application, you can able to see following output.

91 : Country [name=India, capital=New Delhi]
7 : Country [name=Russia, capital=Moscow]





Previous                                                 Next                                                 Home

Monday, 6 March 2017

Spring: Inject set of beans

In my previous post, I explained about how to inject set of strings. In this post, I am going to explain how to inject set of beans. By using <set> and <ref> elements, you can inject set of beans.

Example
 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="favoriteCountries">
   <set>
    <ref bean="india" />
    <ref bean="russia" />
   </set>
  </property>
 </bean>
Following is the complete working application.

Country.java
package com.sample.pojo;

public class Country {
 private String name;
 private String capital;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCapital() {
  return capital;
 }

 public void setCapital(String capital) {
  this.capital = capital;
 }

 @Override
 public String toString() {
  StringBuilder builder = new StringBuilder();
  builder.append("Country [name=").append(name).append(", capital=").append(capital).append("]");
  return builder.toString();
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + ((capital == null) ? 0 : capital.hashCode());
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Country other = (Country) obj;
  if (capital == null) {
   if (other.capital != null)
    return false;
  } else if (!capital.equals(other.capital))
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  return true;
 }

}

Countries.java
package com.sample.pojo;

import java.util.Set;

public class Countries {
 private Set<Country> favoriteCountries;

 public Set<Country> getFavoriteCountries() {
  return favoriteCountries;
 }

 public void setFavoriteCountries(Set<Country> favoriteCountries) {
  this.favoriteCountries = favoriteCountries;
 }

}


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="india" class="com.sample.pojo.Country">
  <property name="name" value="India" />
  <property name="capital" value="New Delhi" />
 </bean>

 <bean id="russia" class="com.sample.pojo.Country">
  <property name="name" value="Russia" />
  <property name="capital" value="Moscow" />
 </bean>

 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="favoriteCountries">
   <set>
    <ref bean="india" />
    <ref bean="russia" />
   </set>
  </property>
 </bean>

</beans>

HelloWorld.java
package com.sample.test;

import java.util.*;

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

import com.sample.pojo.Countries;
import com.sample.pojo.Country;

public class HelloWorld {
 public static void main(String args[]) {
  ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "myConfiguration.xml" });

  Countries countries = context.getBean("demoCountryCapitals", Countries.class);

  Set<Country> favoriteCountries = countries.getFavoriteCountries();

  for (Country country : favoriteCountries) {
   System.out.println(country);
  }

  ((ClassPathXmlApplicationContext) context).close();
 }
}

Run HelloWorld.java, you can able to see following output.
Country [name=India, capital=New Delhi]
Country [name=Russia, capital=Moscow]








Previous                                                 Next                                                 Home