Issue
I have seen in many places
@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) -> {
};
}
}
how does
@Bean
public CommandLineRunner demo(UserRepository repo) {
return (args) -> {
};
}
return an object of type CommandLineRunner
it return a function
(args) -> {
};
I am not able to understand the syntax also.
Can someone help me to understand
Solution
CommandLineRunner is an interface used to indicate that a bean should run when it is contained within a SpringApplication. A Spring Boot application can have multiple beans implementing CommandLineRunner. These can be ordered with @Order
.
It has one abstract method :
void run(String... args) throws Exception
Consider below example:
@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());
}
}
Since CommandLineRunner contains only only abstract method which return nothing so it automatically becomes the functional interface i.e. we can write lambda expression for it.
Above class can be written as :
(args) -> {
logger.info("Loading data..." + args.toString())
};
Coming to Your example :
@Bean
public CommandLineRunner demo(String... args) {
return (args) -> {
};
}
You are expecting to register a bean in Spring Container which implements CommandLineRunner interface so it can converted to lambda expression.
(args) -> {};
Hope this would clarify it enough.
Answered By - Tarun
Answer Checked By - Gilberto Lyons (JavaFixing Admin)