TrickOrTreat
TrickOrTreat

Reputation: 911

What spring annotation needs to place on commandlinerunner interface method in controller

I am trying to implement commandlinerunner interface as lambda expression directly in my controller class of spring boot as its a functional interface. And this was suppose to run as the first thing but it didn't. This works well if i create a separate class and add annotation @Component.

.
.
import org.springframework.boot.CommandLineRunner;

@RestController
@RequestMapping("/api/v1")
public class BookController {

@Autowired
private BookRepository bookRepository;

public BookController(BookRepository bookRepository) {
    this.bookRepository = bookRepository;
}


CommandLineRunner obj = (String... args) -> {

    Book entity1 = new Book("How to stay focused", "Miriyam Bali");
    Book entity2 = new Book("Turn the World", "Cliyo Mathew");
    Book entity3 = new Book("New Heights", "Arsana Jyesh");
    Book entity4 = new Book("Create into leaves", "Nicholas A Buzaz");

    List<Book> books = Arrays.asList(entity1, entity2, entity3, entity4);
        this.bookRepository.saveAll(books);
    };

Upvotes: 0

Views: 100

Answers (1)

Vishal Patel
Vishal Patel

Reputation: 584

You could achieve that by this. it will work.

.
.
import org.springframework.boot.CommandLineRunner;

@RestController
@RequestMapping("/api/v1")
public class BookController {

@Autowired
private BookRepository bookRepository;

public BookController(BookRepository bookRepository) {
    this.bookRepository = bookRepository;
}

@Bean
public CommandLineRunner run() throws Exception {
    return args -> {
        Book entity1 = new Book("How to stay focused", "Miriyam Bali");
        Book entity2 = new Book("Turn the World", "Cliyo Mathew");
        Book entity3 = new Book("New Heights", "Arsana Jyesh");
        Book entity4 = new Book("Create into leaves", "Nicholas A Buzaz");

        List<Book> books = Arrays.asList(entity1, entity2, entity3, entity4);
        this.bookRepository.saveAll(books);
    };
}

Upvotes: 1

Related Questions