Results 1 to 5 of 5

Thread: Safe way to get path in bean configuration?

  1. #1
    Join Date
    Dec 2004
    Posts
    14

    Default Safe way to get path in bean configuration?

    I need to get the path to a directory injected in a bean in my context:

    Code:
    <bean id="myBean" class="my.Class">
       <constructor-arg><value>a java.io.File</value></constructor-arg>
    </bean>
    The constructor wants a File, representing a path to a directory.

    I need this to work across different servlet containers.

  2. #2
    Join Date
    Aug 2004
    Posts
    1,905

    Default

    You would be much better IMHO to use Springs org.springframework.core.io.Resource abstraction: http://www.springframework.org/docs/...resources.html

  3. #3
    Join Date
    Dec 2004
    Posts
    14

    Default

    Yes, I know, but the bean is not written by me.

  4. #4
    Join Date
    Aug 2004
    Posts
    1,905

    Default

    I don't know if there are propertyEditors registered for java.io.Files, so you will either have to write one yourself and register it, or write a FactoryBean:

    Code:
      public FileFactoryBean extends SimpleFactoryBean {
        private final Resource resource;
        public FileFactorybean(final Resource theResource) {
          this.resource = theResource;
        }
        protected abstract Object createInstance() throws Exception {
          return resource.getFile();
        }
      }
    then in your bean factory:

    Code:
    <bean id="myBean" class="my.Class">
       <constructor-arg index="0">
         <bean class="FileFactoryBean">
           <constructor-arg index="0" value="path/to/your/file"/>
         </bean>
       </constructor-arg>
    </bean>
    HTH.

  5. #5
    Join Date
    Dec 2004
    Posts
    14

    Smile

    Thanks! Working great!

    Code:
    public class FileFactoryBean implements FactoryBean {
        
        private final Resource resource;
        
        public FileFactoryBean(final Resource theResource) {
          this.resource = theResource;
        }
    
        public Object getObject() throws Exception {
            return resource.getFile();
        }
        
        public Class getObjectType() {
            return File.class;
        }
        
        public boolean isSingleton() {
            return false;
        }
        
      }
    Code:
    <bean id="fileTemplateLoader" class="TemplateLoader">
       <constructor-arg index="0">
           <bean class="webapp.util.FileFactoryBean">
              <constructor-arg index="0" value="WEB-INF/templates/"/>
            </bean>
       </constructor-arg>
    </bean>
    Found some more info about FactoryBean here: http://blog.arendsen.net/?p=35

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •