gpt4 book ai didi

java - Controller 中的commandlinerunner接口(interface)方法需要添加什么spring注释

转载 作者:行者123 更新时间:2023-12-02 09:26:04 25 4
gpt4 key购买 nike

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

最佳答案

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

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

关于java - Controller 中的commandlinerunner接口(interface)方法需要添加什么spring注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58334864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com