Reputation: 135
I have a List of Book objects which needs to be initialized at Spring boot start up. The list of book is constant and due to DB optimization I don't want to store the data in database and call it every time.
Book class is as below:
Class Book{
private String name;
private String author;
private int pages;
private boolean issued;
}
constructors, getters and setters ....
Suppose I have 3 books as (book1,author1,100,true),(book2,author2,50,false) and (book3,author3,350,true)
Which is the best way of initializing the list while spring startup. Moreover once the initialization is done which is the best way in which I can return it through a Get endpoint method in controller as
@GetMapping(value="/books")
public List<Book> getBooks(){
....
return <List of three books>;
}
Thanks in advance.
Regards, Sameekshya
Upvotes: 0
Views: 5711
Reputation: 1351
@Component
public class BookService implements CommandLineRunner {
private List<Book> bookList = new ArrayList<>();
getters();
@Override
public void run(String...args) throws Exception {
// add book to the bookList
}
}
Access booklist in controller -
@Autowired
private BookService service;
@GetMapping(value="/books")
public List<Book> getBooks(){
....
return service.getBookList();
}
Upvotes: 1