Support this post with a reaction:
Spring Boot starts with @SpringBootApplication
, loads required dependencies using starters, configures them automatically using @EnableAutoConfiguration
, and scans for your components using @ComponentScan
all this with minimal setup!
But there are lots of things happens behind the scenes to simplify development. Here’s a breakdown of the internal working:
1. @SpringBootApplication
and main()
β Entry Point
- This is the starting point of every Spring Boot application.
- It is a meta-annotation that combines:
@Configuration
β Marks the class as a source of bean definitions.@EnableAutoConfiguration
β Enables Spring Bootβs auto-configuration feature.@ComponentScan
β Scans for Spring components (like@Component
,@Service
, etc.) in the current and sub-packages.
- The
main()
method runsSpringApplication.run()
, which starts the embedded server and initializes the application context.
2. Starter Dependencies
- These are pre-configured sets of dependencies (like web, JPA, security) provided by Spring Boot.
- When you add a starter (e.g.,
spring-boot-starter-web
), Spring Boot knows what components to auto-configure. - You donβt need to worry about adding and managing individual library versions.
3. @EnableAutoConfiguration
β Smart Configuration
- This annotation tells Spring Boot to automatically configure your application based on the libraries on the classpath.
- For example:
- If you add
spring-boot-starter-data-jpa
, Spring Boot will try to configure JPA and a DataSource. - If no database is configured manually, it might auto-configure an H2 in-memory database.
- If you add
- It reduces the need for manual configuration in XML or Java.
4. @ComponentScan
β Bean Discovery
- It automatically scans and registers Spring-managed beans (like Controllers, Services, Repositories, etc.) in the package where the main class is located and all its sub-packages.
- This makes dependency injection work without explicitly defining beans.