Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bluearth/37e7fa3ef0010eee658c19b3985abdcf to your computer and use it in GitHub Desktop.
Save bluearth/37e7fa3ef0010eee658c19b3985abdcf to your computer and use it in GitHub Desktop.
What's the difference between a class that is annotated using @SpringApplication and a class that implements ApplicationRunner or CommandLineRunner?

Tags: #spring #spring-boot

Question:

What's the difference between a class that is annotated using @SpringBootApplication and a class that implements ApplicationRunner or CommandLineRunner?

Which one do I need?

Short Answer

You annotate a class with @SpringBootApplication if you want to chuck it into SpringBootApplication constructor or run(...) method. When you chuck such class there Spring will start the snowball effect of conjuring beans. But, at the end of this process you got a fully composed IoC container but no logic started.

If you want to perform some logic after the Application Context is fully setup, then one of your bean has to implements CommandLineRunner (or ApplicationRunner).

There could be more than one bean that implements CommandLineRunner, Spring will run them all. The ordering can be enforced by annotating these classes using @Order

Answer:

Spring Boot ApplicationRunner and CommmandLineRunner allows you to execute your code after Spring Application Context is fully initialized and all declared beans have been loaded.

Spring IoC container helps you to compose the components that are the building block of your application. But when these compositions are all in place, you often need to kick start the main process of your application.

@SpringBootApplication implies @AutoConfiguration. This means when your @SpringBootApplication class is conjured by Spring, Spring knows that it needs to do auto-configuration steps.

@SpringBootApplication implies @ComponentScan. This means when your @SpringBootApplication class is conjured by Spring it will scan for other class marked as @Component or other stereotype attributes (e.g. @Service, @Repository, etc) and conjure those too when needed.

@SpringBootApplication implies @Configuration. This means that this class of yours, Spring will use it's methods marked with @Bean as a factory to conjure beans of the same type as the methods return type when other beans need it.

None of the behavior above gives way for developer to insert application logic after Spring has finished loading. This is where ApplicationRunner and CommandLineRunner fits in. The run method will be invoked after the Application Context has been fully setup and before your application starts servicing requests (in the context of web application)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment