Tuesday, 28 February 2017

Spring: Inject set

By using <set> element, you can inject set.

Exmaple
 <bean id="demoCountryCapitals" name="demoCountryCapitals" class="com.sample.pojo.Countries">
  <property name="countries">
   <set>
    <value>Iceland</value>
    <value>India</value>
    <value>Sri Lanka</value>
    <value>Russia</value>
   </set>
  </property>
 </bean>

Following is the complete working application.

Countries.java
package com.sample.pojo;

import java.util.Set;

public class Countries {
 private Set<String> countries;

 public Set<String> getCountries() {
  return countries;
 }

 public void setCountries(Set<String> countries) {
  this.countries = countries;
 }

}


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="countries">
   <set>
    <value>Iceland</value>
    <value>India</value>
    <value>Sri Lanka</value>
    <value>Russia</value>
   </set>
  </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("demoCountryCapitals", Countries.class);

  Set<String> countryNames = countries.getCountries();

  for (String country : countryNames) {
   System.out.println(country);
  }

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


Run HelloWorld.java, you can able to see following output.
Iceland
India
Sri Lanka
Russia




Previous                                                 Next                                                 Home

No comments:

Post a Comment