春天:@bean CommandlineRunner。它如何返回 CommandlineRunner 类型的对象

San*_*idi 4 java spring-boot

我在很多地方都见过

@SpringBootApplication
public class Application {

    private static final Logger log =
            LoggerFactory.getLogger(Application.class);

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner demo(UserRepository repo) {
        return (args) -> {
        };
    }

}
Run Code Online (Sandbox Code Playgroud)

如何

@Bean
public CommandLineRunner demo(UserRepository repo) {
    return (args) -> {
    };
}
Run Code Online (Sandbox Code Playgroud)

返回类型的对象CommandLineRunner

它返回一个函数

(args) -> {
        };
Run Code Online (Sandbox Code Playgroud)

我也无法理解语法。

有人可以帮助我理解吗

Tar*_*run 5

CommandLineRunner是一个接口,用于指示 bean 包含在 SpringApplication 中时应该运行。Spring Boot 应用程序可以有多个实现CommandLineRunner的 bean 。这些可以通过 订购@Order

它有一个抽象方法:

    void run(String... args) throws Exception
Run Code Online (Sandbox Code Playgroud)

考虑下面的例子:

@Component
public class MyCommandLineRunner implements CommandLineRunner {

    private final Logger logger = LoggerFactory.getLogger(MyCommandLineRunner.class);

    @Override
    public void run(String... args) throws Exception {
        logger.info("Loading data..." + args.toString());

    }
}
Run Code Online (Sandbox Code Playgroud)

由于CommandLineRunner仅包含抽象方法,不返回任何内容,因此它自动成为函数式接口,即我们可以为其编写 lambda 表达式。

上面的类可以写成:

(args) -> { 
    logger.info("Loading data..." + args.toString()) 
};
Run Code Online (Sandbox Code Playgroud)

以你的例子为例:

@Bean
public CommandLineRunner demo(String... args) {
    return (args) -> {
    };
}
Run Code Online (Sandbox Code Playgroud)

您期望在 Spring 容器中注册一个实现CommandLineRunner接口的 bean,以便它可以转换为 lambda 表达式。

(args) -> {};
Run Code Online (Sandbox Code Playgroud)

希望这足以澄清这一点。