Spring - Array configuration using xml bean configuration file


In this example I am going to give example for array configuration in spring application using XML bean configuration file. This is my bean, here I have created the setter and getter method for array variable ("countryArray").

  public class ArrayConfig {
      private String[] countryArray;

      public String[] getCountryArray() {
            return countryArray;
      }

      public void setCountryArray(String[] countryArray) {
            this.countryArray = countryArray;
      }
     
}

This is my beans.xml file. The <array> tag is used for configuring array.
  
<?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-3.1.xsd">
      <!-- Array Configuration -->
      <bean id="arrayConfigBean" class="com.arrayconfig.ArrayConfig">
            <property name="countryArray">
                  <array>
                        <value>India</value>
                        <value>US</value>
                        <value>UK</value>
                        <value>China</value>
                  </array>
            </property>
      </bean>
</beans>

This is my main method for testing.


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

public class ArrayDemo {
      public static void main(String[] args) {
            ApplicationContext context = new FileSystemXmlApplicationContext("classpath:beans.xml");
            ArrayConfig arrayConfig = context.getBean("arrayConfigBean",ArrayConfig.class);
            String countryArray[] = arrayConfig.getCountryArray();
            System.out.println("Country List");
            System.out.println("***************");
            for(String country:countryArray) {
                  System.out.println(country);
            }
      }
}

You will get result like this.

Comments

Popular Posts