Inject a file resource into Spring bean

后端 未结 3 1513
离开以前
离开以前 2021-01-12 09:56

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 ?



        
3条回答
  •  渐次进展
    2021-01-12 10:14

    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:

    
       
    
    

    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.

提交回复
热议问题