【发布时间】:2014-09-19 14:32:11
【问题描述】:
我正在尝试在 Spring @Configuration 类之一中创建 @Bean 期间在 WEB-INF 目录下加载特定资源。
据我所知@ImportResource 仅用于 Spring xml 配置,而不用于其他文件。
带有ClassLoader 的方法不起作用并且总是返回null。
例如:
@Bean
public aBean someBean() {
final URL someFolderDirUrl = WebConfig.class.getClassLoader().getResource("WEB-INF/someFolder");
final URL someFolderDirUrl2 = WebConfig.class.getClassLoader().getResource("/someFolder");
final URL someFolderDirUrl3 = WebConfig.class.getClassLoader().getResource("/WEB-INF/someFolder");
final URL someFolderDirUrl4 = WebConfig.class.getClassLoader().getResource("someFolder");
// final URI someFolderDirUri = new URI("file:/WEB-INF/someFolder");
if(modulesDirUrl != null) {
File someFolderDirFile;
try {
someFolderDirFile = new File(someFolderDirUrl.toURI());
} catch(final URISyntaxException e) {
someFolderDirFile = new File(someFolderDirUrl.getPath());
}
return new aBean(someFolderDirFile);
}
return new aBean();
}
最后所有 someFolderDirUrlX 变量都是null,someFolderDirUri 也是如此。
是否可以在 Spring 的 @Configuration 类中获取一个 File 对象,该对象指向 WEB-INF 中的文件或目录?
【问题讨论】:
-
注入
ResourceLoader以利用 Spring 的资源加载机制,而不是自行破解。 -
不适用于
ClassLoader。getResource用于类路径资源。WEB-INF通常不会放在类路径中。
标签: java spring spring-mvc configuration