Inject a file resource into Spring bean

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.

To get the path of the file: use

Resource rsrc = new ClassPathResource(classpathRelativePath);</code>
<code>rsrc.getFile().getAbsolutePath();
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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