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

时间:2021-06-05 04:15:59

标签: 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) -> {
        };
    }
}

怎么办

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

返回一个 CommandLineRunner 类型的对象

它返回一个函数

(args) -> {
        };

我也无法理解语法。

谁能帮我理解一下

2 个答案:

答案 0 :(得分:1)

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

它有一个抽象方法:

    void run(String... args) throws Exception

考虑下面的例子:

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

    }
}

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

上面的类可以写成:

(args) -> { 
    logger.info("Loading data..." + args.toString()) 
};

以您为例:

@Bean
public CommandLineRunner demo(String... args) {
    return (args) -> {
    };
}

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

(args) -> {};

希望这足以说明问题。

答案 1 :(得分:0)

CommandLineRunner 是一个函数式接口,带有一个返回 void 的方法。

这就是为什么当你写:{};一切正常。

相关问题