开发者

Spring 3.0 inject files as resources

开发者 https://www.devze.com 2023-04-05 22:47 出处:网络
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 po开发者_运维百科ssible to inject the

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 po开发者_运维百科ssible to inject them as a normal Resource?


Here is an easiest way to do it via annotation:

import org.springframework.core.io.Resource;

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


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>


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)


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号