Spring Web: Getting file from web context using Resource?
Is there a way to get a re开发者_如何学运维source 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.
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
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;
}
}
精彩评论