How do I load a resource and use its contents as a string in Spring

前端 未结 5 1025
春和景丽
春和景丽 2020-12-04 17:48

How can I load a Spring resource contents and use it to set a bean property or pass it as an argument constructor?

The resource contains free text.

5条回答
  •  长情又很酷
    2020-12-04 17:56

    daoway answer was very helpful, and following Adrian remark I am adding a configuration snippet similar to daoway's code

    
        
    
    

    From your component

        @Autowired
        private Resource contents;
    
        @PostConstruct
        public void load(){
            try {
                final InputStream inputStream = contents.getInputStream();
                    //use the stream 
                BufferedReader br = new BufferedReader(new InputStreamReader(inputStream ,1024);
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    stringBuilder.append(line).append('\n');
                }
                br.close();
         }catch (IOException e) {
                LOGGER.error(message);
         }
      }
    

提交回复
热议问题