Lambda function returned - trying to understand what this means

610 Views Asked by At

In a simple example of CommandLineRunner from within the main method of a Spring Boot Application class.

Trying to understand the effect/meaning of return args-> lambda function in the run method. The method should return the instance of the CommandLineRunner.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}

@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
    // what happens here? What is the equivalent Java 7 return statement?
    return args -> {
        System.out.println("run is working");   
    };
}
3

There are 3 best solutions below

0
On

Look into "functional interface", added in Java 8. CommandLineRunner is one. That code is equivalent to returning an anonymous class.

1
On

Thanks to the person who clarified it for me. So this would be the corresponding anonymous class, it seems:

@Bean
    public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
        CommandLineRunner runner = new CommandLineRunner() {
            public void run(String... s) {
                System.out.println("run is working");   
            }
        };
        return runner;
    } 
0
On

Thanks I was also looking for the answer of this question. Just to add - CommandLineRunner is an Interface, more precisely to say "functional interface", if I understand it correctly, in springboot that has only one method run(). Actually all the functional interface has only one abstract method, there could be default implementation or static method as well though.

So the point is - when we are returning a lambda in this context, basically we are returning an implementation of that run method of the functional interface commandlinerunner.

Thats how I understood. Some other useful information with example can be found here:

https://www.baeldung.com/spring-boot-console-app

We could also write the same thing as per the below example:

public class SpringBootConsoleApplication 
  implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
      .getLogger(SpringBootConsoleApplication.class);

    public static void main(String[] args) {
        LOG.info("STARTING THE APPLICATION");
        SpringApplication.run(SpringBootConsoleApplication.class, args);
        LOG.info("APPLICATION FINISHED");
    }
 
    @Override
    public void run(String... args) {
        LOG.info("EXECUTING : command line runner");
 
        for (int i = 0; i < args.length; ++i) {
            LOG.info("args[{}]: {}", i, args[i]);
        }
    }
}