Java 在控制器中的commandlinerunner接口方法上需要放置什么spring注释

Java 在控制器中的commandlinerunner接口方法上需要放置什么spring注释,java,spring-boot,Java,Spring Boot,我正试图将commandlinerunner接口作为lambda表达式直接实现在spring boot的控制器类中,作为其功能接口。这本来应该是第一件事,但事实并非如此。如果我创建一个单独的类并添加注释@Component,这将非常有效 . . import org.springframework.boot.CommandLineRunner; @RestController @RequestMapping("/api/v1") public class BookController { @

我正试图将commandlinerunner接口作为lambda表达式直接实现在spring boot的控制器类中,作为其功能接口。这本来应该是第一件事,但事实并非如此。如果我创建一个单独的类并添加注释
@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);
    };
。
.
导入org.springframework.boot.CommandLineRunner;
@RestController
@请求映射(“/api/v1”)
公共类图书管理员{
@自动连线
私人书库;
公共图书管理员(图书存储库图书存储库){
this.bookRepository=bookRepository;
}
CommandLineRunner obj=(字符串…参数)->{
Book entity1=新书(“如何保持专注”,“米里亚姆巴厘岛”);
Book entity2=新书(“扭转世界”、“克里约·马修”);
Book entity3=新书(“新高度”、“Arsana Jyesh”);
Book entity4=新书(“创造树叶”、“尼古拉斯·布扎兹”);
List books=Arrays.asList(entity1、entity2、entity3、entity4);
this.bookRepository.saveAll(图书);
};

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

.
.
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);
    };
}
。
.
导入org.springframework.boot.CommandLineRunner;
@RestController
@请求映射(“/api/v1”)
公共类图书管理员{
@自动连线
私人书库;
公共图书管理员(图书存储库图书存储库){
this.bookRepository=bookRepository;
}
@豆子
public CommandLineRunner run()引发异常{
返回参数->{
Book entity1=新书(“如何保持专注”,“米里亚姆巴厘岛”);
Book entity2=新书(“扭转世界”、“克里约·马修”);
Book entity3=新书(“新高度”、“Arsana Jyesh”);
Book entity4=新书(“创造树叶”、“尼古拉斯·布扎兹”);
List books=Arrays.asList(entity1、entity2、entity3、entity4);
this.bookRepository.saveAll(图书);
};
}

是的,它是……为什么@Bean在这一点上是允许的,而当我尝试时,它却不允许它出现在那里。。?