将文件资源注入Spring bean [英] Inject a file resource into Spring bean
本文介绍了将文件资源注入Spring bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
将一些文件资源注入Spring bean的好方法是什么? 现在,我自动连接ServletContext并按如下所示使用.在Spring MVC中,这样做更优雅吗?
What is a good way to inject some file resource into Spring bean ? Now i autowire ServletContext and use like below. Is more elegant way to do that in Spring MVC ?
@Controller
public class SomeController {
@Autowired
private ServletContext servletContext;
@RequestMapping("/texts")
public ModelAndView texts() {
InputStream in = servletContext.getResourceAsStream("/WEB-INF/file.txt");
// ...
}
}
推荐答案
类似以下内容:
@Controller
public class SomeController {
private Resource resource;
public void setResource(Resource resource) {
this.resource = resource;
}
@RequestMapping("/texts")
public ModelAndView texts() {
InputStream in = resource.getInputStream();
// ...
in.close();
}
}
在您的bean定义中:
In your bean definition:
<bean id="..." class="x.y.SomeController">
<property name="resource" value="/WEB-INF/file.txt"/>
</bean>
这将使用/WEB-INF/file.txt
路径创建一个ServletContextResource
,并将其注入到您的控制器中.
This will create a ServletContextResource
using the /WEB-INF/file.txt
path, and inject that into your controller.
请注意,使用此技术不能使用组件扫描来检测控制器,您需要一个显式的bean定义.
Note you can't use component-scanning to detect your controller using this technique, you need an explicit bean definition.
这篇关于将文件资源注入Spring bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文