Friday, May 4, 2012

Use of Apache commons configuration in Spring framework

I can get benefit if I use Apache commons configuration.
The reason is

I can choose plain text property file or xml based property file. but, mostly better to use xml based property
I can use UTF-8 Encoding, so that I can type most of language characters.
I can set same key name to get list or array or collection so on. So, I can simply get it and run looping clause.
I can get property value based on hierarchy.

I wanted to use on Spring framework. I just set one Spring bean
※ it worked in Spring3, I guess it will work lower version of Spring as well.

 <bean id="xmlConfig" class="org.apache.commons.configuration.XMLConfiguration">
  <constructor-arg type="java.lang.String">
   <value>commons-config.xml</value>
  </constructor-arg>
 </bean>


commons-config.xml file, you can change root element "configuration" as you like

<?xml version="1.0" encoding="ISO-8859-1" ?>
<configuration>
 <countries>
  <country>
   <code>gbr</code>
  </country>
  <country>
   <code>ger</code>
  </country>
  <country>
   <code>ita</code>
  </country>
  <country>
   <code>aut</code>
  </country>
  <country>
   <code>che</code>
  </country>
  <country>
   <code>chfr</code>
  </country>
  <country>
   <code>swe</code>
  </country>
  <country>
   <code>esp</code>
  </country>  
 </countries>
</configuration>

Make a Spring controller and getStringArray from property
package monitor.controller;

import java.util.List;

import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexController {

 private final Log logger = LogFactory.getLog(this.getClass());

 @Autowired private XMLConfiguration config;

 @RequestMapping(value = { "/", "/index" })
 public ModelAndView index() {

  ModelAndView mnv = new ModelAndView();
  String[] countries = config.getStringArray("countries.country.code");
  mnv.addObject("countries", countries);

  mnv.setViewName("index");

  return mnv;
 }

}

No comments:

Post a Comment