将一些文件资源注入Spring bean的好方法是什么?现在我自动装配ServletContext并使用如下所示.在Spring MVC中更优雅的方式吗?
@Controller
public class SomeController {
@Autowired
private ServletContext servletContext;
@RequestMapping("/texts")
public ModelAndView texts() {
InputStream in = servletContext.getResourceAsStream("/WEB-INF/file.txt");
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西:
@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();
}
}
Run Code Online (Sandbox Code Playgroud)
在你的bean定义中:
<bean id="..." class="x.y.SomeController">
<property name="resource" value="/WEB-INF/file.txt"/>
</bean>
Run Code Online (Sandbox Code Playgroud)
这将创建一个ServletContextResource使用/WEB-INF/file.txt路径,并将其注入您的控制器.
请注意,您无法使用组件扫描来使用此技术检测控制器,您需要显式的bean定义.
| 归档时间: |
|
| 查看次数: |
16245 次 |
| 最近记录: |