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");
// ...
}
}
Something like this:
In your bean definition:
This will create a
ServletContextResourceusing the/WEB-INF/file.txtpath, and inject that into your controller.Note you can’t use component-scanning to detect your controller using this technique, you need an explicit bean definition.