How To Load CSV File On Application Start Up In Spring Boot

Posted By : Prakhar Verma | 29-Sep-2017

1. Create a simple Spring Boot application using IDE (STS, Eclipse).

2. Create a Service Bean with @Service annotation.

    When we apply @Service annotation on any class in Spring boot then Spring boot create a object of that

    class on application startup using default constuctor of that class.

3. Service Bean should contain a default constructor.

4. Create a CSV file and put it in a resource directory of spring boot project structure.

 

 

 

5. Create a method for load CSV file and put data of CSV file inside a ArrayList (Example : init() ) in Service Bean.

    On init Method Use @PostConstruct for load CSV File.

 

6. When we apply @PostConstruct annotation on init() method then init() method call after default constructor of Service Bean.

 

 

 

7. We use a method of Utility class which is responsible for reading CSV file and return an ArrayList. this ArrayList are used to

 

8.  Inside Init method we use ResourceLoader of org.springframework.core.io.ResourceLoader package.

 

9.  Spring Boot provide Imlepmentation class of Resource Interface of org.springframework.core.io.Resource package.

 

      getResource() method is used for load any resource from any directory (Example : csv , doc, png , jpeg , git , xls , etc ) .

      Inside get resource we pass the path of CSV file in the form of String. path append a sub string "classpath:".

 

10. For example we have a csv file country.csv inside the "assests/csv/country.csv" directory the actual path is : 

      "classpath:assests/csv/country.csv".

 

11. getResource("classpath:assests/csv/country.csv") return a Object resource of ResourceLoader using Resource object

      we get the InputStream of file.

 

12. We can get InputStream Object by using getInputStream() method of Resource Interface. Input Stream Object

      pass inside the loadCSVFile() method for load data of csv file.

 

13.  loadCSVFile() is a method of KYCUtilities and Its take two parameter first a Class of Bean on whichwe convert csv data in

       the form of object and another is inputStream object.

 

14.  loadCSVFile() method iterate each row of csv file and convert it into the form of object which are provided in parameter. 

   

About Author

Author Image
Prakhar Verma

Prakhar is a Web App Developer. Experienced in Java and always gives his best effort to complete the given task. He is self motivated and fun loving person.

Request for Proposal

Name is required

Comment is required

Sending message..