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:
@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();
}
}
In your bean definition:
<bean id="..." class="x.y.SomeController">
<property name="resource" value="/WEB-INF/file.txt"/>
</bean>
This will create a ServletContextResource
using the /WEB-INF/file.txt
path, 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.
Or just use the @Value
annotation.
For single file:
@Value("classpath:conf/about.xml")
private Resource about;
For multiple files:
@Value("classpath*:conf/about.*")
private Resource[] abouts;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With