Announcement Announcement Module
Collapse
No announcement yet.
Safe way to get path in bean configuration? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • 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
    You would be much better IMHO to use Springs org.springframework.core.io.Resource abstraction: http://www.springframework.org/docs/...resources.html

    Comment


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

      Comment


      • #4
        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.

        Comment


        • #5
          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

          Comment

          Working...
          X