⚡ Spring Boot
Discover Spring Boot. Learn auto-configuration, starters, properties, REST APIs, and Actuator for production-ready applications.
1. What is Spring Boot?
While the Spring Framework is extremely powerful, configuring a Spring application from scratch requires a lot of boilerplate (setting up DispatcherServlets, configuring Hibernate, mapping components, handling dependencies, setting up Tomcat).
Spring Boot is an extension of the Spring framework that eliminates this boilerplate configuration. It takes an opinionated approach to configuration, providing production-ready defaults so you can start developing your application immediately.
| Feature | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Requires explicit XML or Java config for everything | Auto-configuration based on classpath |
| Dependencies | Manual dependency version management | "Starter" POMs with tested version combinations |
| Server Deployment | Requires external application server (Tomcat/Jetty) | Embedded server out-of-the-box |
| Production Ready | Need to build monitoring/metrics manually | Built-in via Spring Boot Actuator |
2. Creating a Spring Boot Project
The easiest way to start a Spring Boot project is using Spring Initializr (start.spring.io). It generates the project structure and pom.xml file for you.
Starter Dependencies
Instead of manually adding dozens of related libraries, Spring Boot provides "Starters". For example, adding spring-boot-starter-web brings in Spring MVC, REST support, Jackson (for JSON), and an embedded Tomcat server.
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> </parent> <dependencies> <!-- For building REST APIs, includes Tomcat --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- For database access --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> </dependencies>
3. @SpringBootApplication and Application Entry Point
A Spring Boot application is bootstrapped using a main method and the @SpringBootApplication annotation.
@SpringBootApplication is a convenience annotation that combines three powerful annotations:
- @Configuration: Tags the class as a source of bean definitions.
- @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings (e.g., if Tomcat is on the classpath, set up a web server).
- @ComponentScan: Tells Spring to look for other components, configurations, and services in the current package and its sub-packages.
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { // Starts the Spring Application Context and the Embedded Server SpringApplication.run(MyApplication.class, args); } }
4. Auto-Configuration Magic
Auto-configuration attempts to guess and configure beans that you are likely to need. It relies on @Conditional annotations behind the scenes.
For example, if Spring Boot sees spring-data-jpa and h2 on the classpath, it automatically configures a DataSource, an EntityManagerFactory, and a TransactionManager because of conditions like @ConditionalOnClass and @ConditionalOnMissingBean.
--debug flag (or setting debug=true in your properties).
5. Application Properties & YAML
Spring Boot allows externalized configuration using application.properties or application.yml.
YAML is often preferred for its clean hierarchical structure.
server: port: 8080 spring: datasource: url: jdbc:h2:mem:testdb username: sa password: password jpa: hibernate: ddl-auto: update show-sql: true
@ConfigurationProperties
To bind properties in your file to strongly-typed Java objects, use @ConfigurationProperties.
@Component @ConfigurationProperties(prefix = "app.mail") public class MailConfig { private String host; private int port; // getters and setters }
6. Complete REST API Example
Let's build a fully functioning "Todo" API connected to an in-memory database.
package com.example.demo.model; import jakarta.persistence.*; @Entity public class Todo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private boolean completed; // Constructors, Getters, and Setters... }
package com.example.demo.repository; import com.example.demo.model.Todo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TodoRepository extends JpaRepository<Todo, Long> { // Spring Data JPA automatically provides CRUD methods! }
package com.example.demo.controller; import com.example.demo.model.Todo; import com.example.demo.repository.TodoRepository; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/api/todos") public class TodoController { private final TodoRepository repository; public TodoController(TodoRepository repository) { this.repository = repository; } @GetMapping public List<Todo> getAllTodos() { return repository.findAll(); } @PostMapping public Todo createTodo(@RequestBody Todo todo) { return repository.save(todo); } }
7. Spring Boot Actuator
Actuator brings production-ready features to your application without writing code. It exposes endpoints to monitor your app's health, gather metrics, and analyze traffic.
Include the spring-boot-starter-actuator dependency and expose endpoints in properties:
management.endpoints.web.exposure.include=* management.endpoint.health.show-details=always
Now, you can visit http://localhost:8080/actuator/health to see system status, DB connection status, and disk space details.
8. Exception Handling in REST
Use @ControllerAdvice and @ExceptionHandler to globally handle exceptions and return clean, standardized JSON errors.
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity<String> handleIllegalArgument(IllegalArgumentException ex) { return ResponseEntity .status(HttpStatus.BAD_REQUEST) .body(ex.getMessage()); } }
9. Testing Spring Boot Applications
Spring Boot provides excellent support for writing unit and integration tests.
@SpringBootTest: Loads the entire application context for integration testing.@WebMvcTest: Loads only the web layer (Controllers) for faster testing without spinning up a real server.@DataJpaTest: Loads only the persistence layer for testing Repositories with an in-memory DB.
@WebMvcTest(TodoController.class) class TodoControllerTest { @Autowired private MockMvc mockMvc; @MockBean private TodoRepository repository; @Test void shouldReturnEmptyList() throws Exception { mockMvc.perform(get("/api/todos")) .andExpect(status().isOk()) .andExpect(content().json("[]")); } }