简体   繁体   中英

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);
    };

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);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM