4

Is there a way to get a resource in a spring web application using a simple Resource? I am trying not to pass any context, and need to obtain a file from the WEB-INF/freemarker/email/ directory.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
wuntee
  • 12,170
  • 26
  • 77
  • 106

2 Answers2

4

No. Since the WEB-INF/freemaker/email is not on the classpath, you need to pass ServletContext. As you mention Resource, you can use:

Resource resource = new ServletContextResource(servletContext, resourcePath);

Just don't pass the ServletContext to the service layer. Pass the Resource instead.

If you want to obtain the template from the classpath, place it there. That is, for example, in:

WEB-INF/classes/freemaker/email

Then you can use ClassPathResource

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • specifically in this case, i am trying to get a freemarker template - even using ClasspathResource, and passing the full filename to the Freemarker Template i get exceptions. I am just looking for the easiest way to obtain a ftl from the classpath. You have any idea, or should i create a new question? – wuntee Jun 10 '10 at 21:22
1

You can implement org.springframework.context.ResourceLoaderAware interface in your class and get access to ResourceLoader. That it's rather easy to use.

public class SomeService implements ResourceLoaderAware {
   private ResourceLoader resourceLoader;

   public void doSomething() {
       Resource skin = resourceLoader.getResource("myfile.txt");
   }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

}
Pavel Molchanov
  • 2,299
  • 1
  • 19
  • 24