Tuesday, September 18, 2007

Automatic Directory Creation via Spring Application Context File

Spring lets you define property editors that convert from a text representation to an object representation. We can hook into this feature to automate directory creation like this:
public class DirectoryEditor extends PropertyEditorSupport {

 public void setAsText(String textValue) {
  File f = new File(textValue);
  if (!f.exists()) {
   if (!f.mkdirs()) {
    throw new ConfigurationException("Unable To Create Directory: [" + textValue + "]");
   }
  } else if (!f.isDirectory()) {
   throw new ConfigurationException("File Is Not a Directory: [" + textValue + "]");
  }
  setValue(new Directory(textValue));
 }
 
}
Then create a bean definition so that Spring knows about it:
  <bean id="customEditorConfigurer"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
      <map>
        <entry key="com.twintechs.spring.Directory">
          <bean id="directoryEditor" class="com.twintechs.spring.DirectoryEditor" />
        </entry>
      </map>
    </property>
</bean>
Then create a Directory class:
public class Directory {

 private String name;

 public Directory(String _name) {
  super();
  this.name = _name;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
 
}
The last step is to use the Directory class in place of the String class in any Java objects.
Post a Comment