Spring 3.0将文件注入资源

时间:2011-09-20 11:47:25

标签: java spring resources

在我的Spring 3.0应用程序中,/WEB-INF/dir中有一些资源。在运行时,我需要其中一些作为InputStream(或其他类型)。我怎样才能找回它们?是否可以将它们注入正常Resource

5 个答案:

答案 0 :(得分:67)

这是通过注释执行此操作的最简单方法:

import org.springframework.core.io.Resource;

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

答案 1 :(得分:6)

根据定义,所有ApplicationContext都是ResourceLoader。这意味着它们能够解析在其配置中找到的任何资源字符串。考虑到这一点,您可以使用接受org.springframework.core.io.Resource的setter声明目标bean。然后,在配置目标bean时,只需在属性的值中使用资源路径。 Spring会尝试将配置中的String值转换为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>

答案 2 :(得分:2)

你应该可以使用:

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

其中appContext是您的Spring ApplicationContext(特别是WebApplicationContext,因为您有一个webapp)

答案 3 :(得分:1)

这是检索类路径资源的完整示例。我用它来获取具有非常复杂查询的SQL文件,我不想将它存储在Java类中:

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

答案 4 :(得分:0)

如果您不想引入对Spring的依赖,请按照此处详述的方法: Populate Spring Bean's File field via Annotation