Search code examples
javaspringspring-bootspring-annotationsspring-ioc

How to read a file and assign it to an ArrayList in spring?


Consider the following classes:

public class Store {
    private final ArrayList<String> store;
    public ArrayList<String> getStore() {
        return store;
    }
    public Store(ArrayList<String> store){
        this.store = store;
    }
}

I have a text file called input.txt
I have a normal controller which is annotated with @RestController as follows:

@RestController
@RequestMapping(value="/test")
public class Controller {

    .
    .
    .

}

I need to do the following operations:

  1. Read input.txt by using Files.readAllLines(path,cs) (from JDK 1.7)
  2. Set the returned value(List<String>) to Store.store
  3. I wanna use Spring annotations all the way (I'm writing a spring-boot application)
  4. I need Store to be a Singleton bean.
  5. The store needs to be initialized during the bootstrapping of my application.

This question might be too vague, but I have absolutely no idea about how to make it more specific.

P.S.
I'm a newbie to Spring.


Solution

  • It seems like using Constructor Injection would be ideal.

    public class Store {
        private final List<String> storeList;
    
        @Autowired
        public Store(@Value("${store.file.path}") String storeFilePath) throws IOException {
                File file = new File(storeFilePath);
                storeList = Files.readAllLines(file.toPath());
        }
    }
    

    you will want to add the store.file.path property to your properties file that is read in by your spring context. You will also want to add a bean definition for Store

    <bean id="Store" class="com.test.Store" />

    Then your Rest Controller can look something like this:

    @RestController
    @RequestMapping(value="/store")
    public class StoreRestController {
    
        @Autowired
        Store store;
    
        @RequestMapping(value="/get", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<Store> getStore(HttpServletRequest request) {
            ResponseEntity<Store> response = new ResponseEntity<Store>(store, HttpStatus.OK);
            return response;
        }
    }
    

    There's a couple different ways to write your injection & controller so do some research and use the method that best suites your needs.