# Spring Boot Spring Boot is an opinionated framework that simplifies building production-grade Spring applications with minimal configuration. It provides auto-configuration, embedded servers, and a comprehensive set of starter dependencies that enable developers to create stand-alone, production-ready applications that can be started with `java -jar`. Spring Boot eliminates boilerplate configuration by making intelligent defaults while allowing easy customization when requirements diverge from those defaults. The framework's core functionality includes automatic configuration of Spring and third-party libraries, embedded servlet containers (Tomcat, Jetty, Undertow), externalized configuration via properties/YAML files, production-ready features like health checks and metrics through Actuator, and zero code generation with no XML configuration required. Spring Boot supports both traditional servlet-based web applications and reactive applications, with seamless integration into the broader Spring ecosystem including Spring Data, Spring Security, and Spring Cloud. ## SpringApplication - Bootstrap and Launch The `SpringApplication` class bootstraps a Spring application from a Java main method. It creates an appropriate `ApplicationContext`, registers command-line arguments as Spring properties, refreshes the context to load all beans, and triggers any `CommandLineRunner` beans. ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @RestController public class MyApplication { @GetMapping("/") public String home() { return "Hello World!"; } public static void main(String[] args) { SpringApplication.run(MyApplication.class, args); } } ``` ## SpringApplication Customization For advanced configuration, create a `SpringApplication` instance and customize it before running. You can disable the banner, set profiles, configure lazy initialization, and more. ```java import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(MyApplication.class); app.setBannerMode(Banner.Mode.OFF); app.setLazyInitialization(true); app.run(args); } } ``` ## SpringApplicationBuilder - Fluent API The `SpringApplicationBuilder` provides a fluent API for building application context hierarchies with parent/child relationships. ```java import org.springframework.boot.builder.SpringApplicationBuilder; public class MyApplication { public static void main(String[] args) { new SpringApplicationBuilder() .sources(ParentConfiguration.class) .child(ChildConfiguration.class) .bannerMode(Banner.Mode.OFF) .run(args); } } ``` ## REST Controller with Spring MVC Spring MVC's `@RestController` and `@RequestMapping` annotations handle incoming HTTP requests and return JSON responses automatically. ```java import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @RestController @RequestMapping("/api/users") public class UserController { private final List users = new CopyOnWriteArrayList<>(); @GetMapping public List getAllUsers() { return users; } @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return users.stream() .filter(u -> u.getId().equals(id)) .findFirst() .orElseThrow(() -> new UserNotFoundException(id)); } @PostMapping public User createUser(@RequestBody User user) { users.add(user); return user; } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { // Update logic return user; } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { users.removeIf(u -> u.getId().equals(id)); } } ``` ## Externalized Configuration Spring Boot supports externalized configuration through properties files, YAML, environment variables, and command-line arguments. Properties can be injected using `@Value` or bound to structured objects with `@ConfigurationProperties`. ```yaml # application.yml server: port: 8080 servlet: context-path: /api spring: application: name: my-app datasource: url: jdbc:mysql://localhost/mydb username: dbuser password: dbpass myapp: feature: enabled: true max-connections: 100 ``` ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "myapp.feature") public class FeatureProperties { private boolean enabled; private int maxConnections; // getters and setters public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public int getMaxConnections() { return maxConnections; } public void setMaxConnections(int maxConnections) { this.maxConnections = maxConnections; } } ``` ## DataSource Configuration Spring Boot auto-configures a `DataSource` with connection pooling (HikariCP by default). Configure database connections through properties. ```yaml # application.yml spring: datasource: url: jdbc:postgresql://localhost:5432/mydb username: postgres password: secret hikari: maximum-pool-size: 20 minimum-idle: 5 connection-timeout: 30000 jpa: hibernate: ddl-auto: validate show-sql: true properties: hibernate: format_sql: true ``` ```java import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration public class DataSourceConfig { @Bean public DataSource customDataSource() { return DataSourceBuilder.create() .driverClassName("org.postgresql.Driver") .url("jdbc:postgresql://localhost:5432/mydb") .username("postgres") .password("secret") .build(); } } ``` ## Actuator Health Endpoint The health endpoint provides application health information for monitoring and container orchestration platforms like Kubernetes. ```bash # Retrieve application health curl -X GET http://localhost:8080/actuator/health # Response { "status": "UP", "components": { "db": { "status": "UP", "details": { "database": "PostgreSQL", "validationQuery": "isValid()" } }, "diskSpace": { "status": "UP", "details": { "total": 499963174912, "free": 250000000000, "threshold": 10485760 } } } } # Retrieve health of a specific component curl -X GET http://localhost:8080/actuator/health/db ``` ## Actuator Metrics Endpoint The metrics endpoint provides access to application metrics for diagnostics. Use an external metrics backend (Prometheus, Datadog, etc.) for production monitoring. ```bash # Retrieve available metric names curl -X GET http://localhost:8080/actuator/metrics # Response { "names": [ "jvm.memory.used", "jvm.memory.max", "http.server.requests", "system.cpu.usage", "process.uptime" ] } # Retrieve a specific metric curl -X GET http://localhost:8080/actuator/metrics/jvm.memory.max # Response { "name": "jvm.memory.max", "description": "The maximum amount of memory", "baseUnit": "bytes", "measurements": [ { "statistic": "VALUE", "value": 5368709120 } ], "availableTags": [ { "tag": "area", "values": ["heap", "nonheap"] }, { "tag": "id", "values": ["G1 Eden Space", "Metaspace"] } ] } # Drill down with tags curl -X GET "http://localhost:8080/actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace" ``` ## Actuator Loggers Endpoint The loggers endpoint allows runtime viewing and modification of logger levels without restarting the application. ```bash # Retrieve all loggers curl -X GET http://localhost:8080/actuator/loggers # Retrieve a specific logger curl -X GET http://localhost:8080/actuator/loggers/com.example # Response { "configuredLevel": null, "effectiveLevel": "INFO" } # Set log level at runtime curl -X POST http://localhost:8080/actuator/loggers/com.example \ -H "Content-Type: application/json" \ -d '{"configuredLevel": "DEBUG"}' # Clear a configured log level curl -X POST http://localhost:8080/actuator/loggers/com.example \ -H "Content-Type: application/json" \ -d '{}' ``` ## Actuator Configuration Configure which actuator endpoints are exposed and their access levels through properties. ```yaml # application.yml management: endpoints: web: exposure: include: health,info,metrics,loggers,env base-path: /actuator endpoint: health: show-details: always show-components: always shutdown: access: unrestricted server: port: 9090 # Separate management port ``` ## Metrics with Micrometer Spring Boot auto-configures Micrometer for application metrics. Add registry dependencies for your monitoring system (Prometheus, Datadog, etc.). ```java import io.micrometer.core.instrument.Counter; import io.micrometer.core.instrument.MeterRegistry; import org.springframework.stereotype.Service; @Service public class OrderService { private final Counter ordersCreated; public OrderService(MeterRegistry registry) { this.ordersCreated = Counter.builder("orders.created") .description("Number of orders created") .tag("type", "online") .register(registry); } public Order createOrder(Order order) { // Business logic ordersCreated.increment(); return order; } } ``` ```yaml # Prometheus configuration management: prometheus: metrics: export: enabled: true endpoints: web: exposure: include: prometheus ``` ## Testing with @SpringBootTest Spring Boot provides comprehensive testing support with auto-configuration for various test scenarios. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.test.web.server.LocalServerPort; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class MyApplicationTests { @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test void contextLoads() { } @Test void homeEndpointReturnsHelloWorld() { String response = restTemplate.getForObject( "http://localhost:" + port + "/", String.class ); assertThat(response).isEqualTo("Hello World!"); } } ``` ## Slice Testing with @WebMvcTest Use slice tests to test specific layers in isolation with auto-configured mocks. ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import static org.mockito.BDDMockito.given; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @WebMvcTest(UserController.class) class UserControllerTest { @Autowired private MockMvc mockMvc; @MockBean private UserService userService; @Test void getUserReturnsUser() throws Exception { given(userService.findById(1L)) .willReturn(new User(1L, "John")); mockMvc.perform(get("/api/users/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("John")); } } ``` ## JMS Messaging with ActiveMQ Spring Boot auto-configures JMS infrastructure for messaging with ActiveMQ or Artemis. ```yaml # application.yml spring: artemis: mode: native broker-url: tcp://localhost:61616 user: admin password: secret ``` ```java import org.springframework.jms.annotation.JmsListener; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Service; @Service public class MessageService { private final JmsTemplate jmsTemplate; public MessageService(JmsTemplate jmsTemplate) { this.jmsTemplate = jmsTemplate; } public void sendMessage(String destination, String message) { jmsTemplate.convertAndSend(destination, message); } @JmsListener(destination = "order-queue") public void receiveOrder(String orderJson) { System.out.println("Received order: " + orderJson); // Process order } } ``` ## Building and Running Build and run Spring Boot applications using Gradle or Maven with embedded servers. ```bash # Build with Gradle ./gradlew build # Run the application java -jar build/libs/myapp-0.0.1-SNAPSHOT.jar # Run with custom properties java -jar myapp.jar --server.port=9000 --spring.profiles.active=prod # Build with Maven ./mvnw package # Run with Maven ./mvnw spring-boot:run # Publish to local Maven repository ./gradlew publishToMavenLocal ``` ## Summary Spring Boot is designed for building microservices and standalone applications with minimal configuration overhead. Its primary use cases include creating REST APIs, building web applications with embedded servers, implementing event-driven architectures with messaging, and deploying to cloud platforms. The framework excels at rapid development through its starter dependencies, auto-configuration, and production-ready features like health checks, metrics, and externalized configuration. Integration patterns revolve around Spring's dependency injection, auto-configuration mechanism, and the extensive ecosystem of Spring projects. Applications typically define components using annotations (`@Service`, `@Repository`, `@Controller`), configure behavior through properties/YAML files, and leverage Actuator for production monitoring. The framework supports both traditional blocking I/O with Spring MVC and non-blocking reactive programming with Spring WebFlux, making it suitable for a wide range of application architectures from simple REST services to complex distributed systems.