Inject a file resource into Spring bean

Something like this:

public class SomeController {

    private Resource resource;

    public void setResource(Resource resource) {
        this.resource = resource;

    public ModelAndView texts() {
        InputStream in = resource.getInputStream();
        // ...

In your bean definition:

<bean id="..." class="x.y.SomeController">
   <property name="resource" value="/WEB-INF/file.txt"/>

This will create a ServletContextResource using the /WEB-INF/file.txt path, and inject that into your controller.

To get the path of the file: use

Resource rsrc = new ClassPathResource(classpathRelativePath);</code>

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s