为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

莫回无 2023-10-13 09:51:03
我正在尝试直接在 Spring Boot 的控制器类中将 commandlinerunner 接口实现为 lambda 表达式,作为其功能接口。这本来应该作为第一件事运行,但它没有。如果我创建一个单独的类并添加注释,这会很有效@Component。..import org.springframework.boot.CommandLineRunner;@RestController@RequestMapping("/api/v1")public class BookController {@Autowiredprivate 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);    };
查看完整描述

1 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

你可以通过这个来实现这一点。它会起作用的。


.

.

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

    };

}


查看完整回答
反对 回复 2023-10-13
  • 1 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信