3

I have a bean that has a property of type File. I want that property to end up pointing to a file under WEB-INF.

It seems to me that the ServletContextResourceLoader should have that job, somehow, but nothing I try seems to do the job.

I'm trying to avoid resorting to something like this in the Java code.

Community
  • 1
  • 1
bmargulies
  • 97,814
  • 39
  • 186
  • 310

1 Answers1

4

If that property has to remain as type "File", then you're going to have to jump through some hoops.

It would be better, if possible, to refactor the bean to have a Resource property, in which case you can inject the resource path as a String, and Spring will construct a ServletContextResource for you. You can then obtain the File from that using the Resource.getFile() method.

public class MyBean {

   private File file;

   public void setResource(Resource resource) {
      this.file = resource.getFile();
   }
}

<bean class="MyBean">
   <property name="resource" value="/WEB-INF/myfile">
</bean>
skaffman
  • 398,947
  • 96
  • 818
  • 769
  • Oh, I expected Spring to have a default Resource editor that would take Resource to File via exactly your recipe. Silly me. I can take your advice, though it then promptly runs into some trouble with the jetty-maven-plugin which is fodder for another question another day. – bmargulies Jul 11 '10 at 22:43
  • @bmargulies: If you try to inject a String value into a `File` property, then Spring will just convert directly to a `File` using `new File(String)`, which isn't what you need. – skaffman Jul 11 '10 at 22:51