控制器中的commandlinerunner接口方法需要添加什么spring注释

我正在尝试直接在 Spring Boot 的控制器类中将 commandlinerunner 接口实现为 lambda 表达式,作为其功能接口。这本来应该作为第一件事运行,但它没有。如果我创建一个单独的类并添加注释,这会很有效@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);

    };


莫回无
浏览 73回答 1
1回答

潇湘沐

你可以通过这个来实现这一点。它会起作用的。..import org.springframework.boot.CommandLineRunner;@RestController@RequestMapping("/api/v1")public class BookController {@Autowiredprivate BookRepository bookRepository;public BookController(BookRepository bookRepository) {&nbsp; &nbsp; this.bookRepository = bookRepository;}@Beanpublic CommandLineRunner run() throws Exception {&nbsp; &nbsp; return args -> {&nbsp; &nbsp; &nbsp; &nbsp; Book entity1 = new Book("How to stay focused", "Miriyam Bali");&nbsp; &nbsp; &nbsp; &nbsp; Book entity2 = new Book("Turn the World", "Cliyo Mathew");&nbsp; &nbsp; &nbsp; &nbsp; Book entity3 = new Book("New Heights", "Arsana Jyesh");&nbsp; &nbsp; &nbsp; &nbsp; Book entity4 = new Book("Create into leaves", "Nicholas A Buzaz");&nbsp; &nbsp; &nbsp; &nbsp; List<Book> books = Arrays.asList(entity1, entity2, entity3, entity4);&nbsp; &nbsp; &nbsp; &nbsp; this.bookRepository.saveAll(books);&nbsp; &nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java