Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject a file resource into Spring bean

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");
        // ...
    }
}
like image 430
marioosh Avatar asked Sep 02 '11 06:09

marioosh


2 Answers

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.

like image 173
skaffman Avatar answered Oct 11 '22 23:10

skaffman


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;
like image 38
foal Avatar answered Oct 12 '22 00:10

foal