wuntee
wuntee

Reputation: 12490

Spring Web: Getting file from web context using Resource?

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.

Upvotes: 4

Views: 2485

Answers (2)

Pavel Molchanov
Pavel Molchanov

Reputation: 2419

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;
    }

}

Upvotes: 1

Bozho
Bozho

Reputation: 597382

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

Upvotes: 4

Related Questions