Spring 3.0将文件注入资源

Ran*_*ize 38 java resources spring

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

Nik*_*rov 70

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

import org.springframework.core.io.Resource;

@Value("classpath:<path to file>")
private Resource cert;
Run Code Online (Sandbox Code Playgroud)


Rya*_*ord 6

ApplicationContext根据定义,所有s都是ResourceLoaders.这意味着它们能够解析在其配置中找到的任何资源字符串.考虑到这一点,您可以使用接受的setter来声明目标bean org.springframework.core.io.Resource.然后,在配置目标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>
Run Code Online (Sandbox Code Playgroud)