Spring 3.0 inject files as resources

2019-01-23 11:37发布

问题:

In my Spring 3.0 app, I have some resources in /WEB-INF/dir. At runtime I need some of them as an InputStream (or some other type). How can I retrieve them? Is it possible to inject them as a normal Resource?

回答1:

Here is an easiest way to do it via annotation:

import org.springframework.core.io.Resource;

@Value("classpath:<path to file>")
private Resource cert;


回答2:

All ApplicationContexts are, by definition, ResourceLoaders. This means that they are capable of resolving any resource strings found within their configuration. With this in mind, you can declare your target bean with a setter that accepts an org.springframework.core.io.Resource. Then when you configure the target bean, just use a resource path in the value for the property. Spring will attempt to convert the String value in your configuration into a Resource.

public class Target {
  private Resource resource;
  public void setResource(final Resource resource) {
    this.resource = resource;
  }
}

//configuration
<beans>
  <bean id="target" class="Target">
    <property name="resource" value="classpath:path/to/file"/>
  </bean>
</beans>


回答3:

You should be able to use :

Resource resource = appContext.getResource("classpath:<your resource name>");
InputStream is = resource.getInputStream();

where appContext is your Spring ApplicationContext (specifically, a WebApplicationContext, since you have a webapp)



回答4:

Here's a full example to retrieve a classpath resource. I use it to grab SQL files that have really complex queries which I don't want to store in Java classes:

public String getSqlFileContents(String fileName) {
    StringBuffer sb = new StringBuffer();
    try {
        Resource resource = new ClassPathResource(fileName);
        DataInputStream in = new DataInputStream(resource.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        while ((strLine = br.readLine()) != null) {
            sb.append(" " + strLine);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return sb.toString();
}


回答5:

If you do not want to introduce dependency on Spring, follow approach detailed here: Populate Spring Bean's File field via Annotation