Spring Boot Quickstart
Spring Boot is an opinionated framework that simplifies the creation of stand-alone, production-grade Spring-based applications. It takes the “convention over configuration” approach.1. The Magic of Spring Initializr
You rarely start a Spring project from scratch. You use the Spring Initializr.- Go to start.spring.io
- Project: Maven / Gradle (We’ll use Maven for this course)
- Language: Java
- Spring Boot: 3.x.x (Latest stable)
- Project Metadata:
- Group:
com.devweekends - Artifact:
demo - Packaging:
Jar - Java: 17
- Group:
- Dependencies (Add these):
- Spring Web: For building REST APIs (uses Tomcat as default embedded server).
- Spring Boot DevTools: For fast feedback loops (auto-restart).
- Lombok: To reduce boilerplate code.
2. Project Structure
The Entry Point
@SpringBootApplication annotation is a convenience annotation that adds all of the following:
@Configuration: Tags the class as a source of bean definitions.@EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings (e.g., ifspring-webis on the classpath, setup Tomcat).@ComponentScan: Tells Spring to look for other components, configurations, and services in thecom/devweekends/demopackage.
3. Your First REST Controller
Create a new fileHelloController.java next to DemoApplication.java.
@RestController: Marks this class as a request handler where every method returns a domain object directly (JSON/XML) instead of a view.@GetMapping("/hello"): Maps HTTP GET requests to/helloto thesayHello()method.
4. Running the Application
In your terminal (or IDE):Tomcat started on port(s): 8080 (http)
Open http://localhost:8080/hello in your browser. You should see “Hello, Dev Weekends!“.
5. Dependency Injection (DI) Basics
Spring’s core is the Application Context (the IoC container). It manages the lifecycle of your objects (Beans). Instead ofnew Service(), you ask Spring to give you an instance.
6. Spring Boot Internals: How it Works
Many developers use@SpringBootApplication without knowing what it does. It’s a compound annotation:
@SpringBootConfiguration: Just a specialized@Configuration.@ComponentScan: Scans the current package and sub-packages for Components.@EnableAutoConfiguration: The Magic.
How Auto-Configuration Works
Spring Boot looks at the classpath.- Is
spring-webmvcon the classpath? -> Configure DispatcherServlet. - Is
h2on the classpath? -> Configure DataSource. - Is
hibernate-coreon the classpath? -> Configure EntityManagerFactory.
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports to find configuration classes and applies them conditionally (@ConditionalOnClass, @ConditionalOnMissingBean).
7. Bean Scopes & Lifecycle
By default, all beans are Singletons (created once per app). But you can change this.Scopes
- Singleton (Default): One instance per container.
- Prototype: A new instance every single time it is requested.
- Request: One instance per HTTP Request.
- Session: One instance per HTTP Session.
Lifecycle Callbacks
Sometimes you need to run logic right after a bean is created (e.g., open a socket) or before it dies (e.g., close file).8. Type-Safe Configuration
Stop using@Value("${my.config}"). Ideally, group related properties into a POJO.
application.yml
MailConfig anywhere!
9. Deep Dive: The IoC Container
The Inversion of Control (IoC) container is the heart of Spring. It manages the lifecycle of your objects (Beans).BeanFactory vs ApplicationContext
- BeanFactory: The root interface. Provides basic features (DI). Lazy loading.
- ApplicationContext: A sub-interface. Adds enterprise specific functionality:
- Internationalization (i18n).
- Event publishing.
- Web application support.
- Eager loading (instantiates singletons on startup), which is better for detecting errors early.
In Spring Boot,SpringApplication.run()returns anApplicationContext.
10. Dependency Injection Patterns
How should you inject dependencies?1. Field Injection (Avoid)
- Pros: Concise.
- Cons: Hides dependencies. Impossible to unit test without reflection/mocks. Creates circular dependency risks.
2. Setter Injection (Optional Deps)
- Pros: Allows optional dependencies (can re-configure later).
- Cons: Bean is not immutable.
3. Constructor Injection (Recommended)
- Pros:
- Immutability: Fields can be
final. - Testability: Just pass mocks in
new UserController(mockService). - Safety: Object is fully initialized before use.
- Circular Dependency Detection: Fails fast at startup if A -> B -> A.
- Immutability: Fields can be
multiple Implementations? Use @Qualifier or @Primary
If you haveSmsNotificationService and EmailNotificationService implementing NotificationService, Spring gets confused.
@Primary: The default choice.@Qualifier("sms"): Specific choice injecting time.
11. Advanced Bean Lifecycle
It’s not just “Create -> Use -> Destroy”.BeanPostProcessors (BPP)
These are hooks that allow you to modify beans before they are fully initialized. Example: How@Transactional works.
Spring has a BPP that scans for @Transactional. If found, it wraps your bean in a Proxy (CGLIB or JDK Dynamic Proxy) before handing it to the container. The container never holds your actual class, only the Proxy!