Basic Concepts and Practical Usage of Spring Boot
Why Adopt Spring Boot
Spring serves as a lightweight alternative to legacy J2EE/EJB architectures, enabling developers to implement enterprise-grade functionality using Plain Old Java Objects (POJOs) via Dependency Injection and Aspect-Oriented Programming, without the overhead of heavyweight EJBs. Key strengths of the Spring framework include:
- Reduced coupling between application components
- Built-in enterprise services like transaction management and web services
- Native AOP support
- Seamless integration with all major Java frameworks
- Minimal code intrusion
- High flexibility, allowing developers to use only the parts of Spring they need without mandatory full framework dependency
While Spring’s core code is lightweight, its configuration workflow is notoriously cumbersome. Even as configurations evolved from XML to annotations and Java-based configs, manual setup still consumes significant development time. Additionally, managing project dependencies is error-prone and time-consuming: developers must manually resolve correct artifact coordinates and their transitive dependencies, with version mismatches often causing crippling compatibility issues. Spring also lacks native support for distributed systems, and traditional Spring MVC has overly flexible controller patterns without a standardized base controller, plus excessive boilerplate code in JSP views.
Spring Boot does not add new functionality to the Spring framework; instead, it provides a streamlined, faster way to build Spring-based applications. Core characteristics of Spring Boot include:
- Faster onboarding for new Spring developers
- Opinionated out-of-the-box setup with no code generation or XML configuration, with easy overrides for custom requirements
- Built-in non-functional enterprise features like embedded web servers, security, metrics, health checks, and externalized configuration
Spring Boot’s two core features are:
- Starter Dependencies: These are pre-configured Maven Project Object Model (POM) files that bundle all required transitive dependencies for a specific functionality set. In short, starter dependencies package coordinated libraries for a given use case and include default configurations to reduce manual setup.
- Auto-Configuration: A runtime process executed during application startup that automatically determines which Spring configurations to apply based on classpath contents, environment variables, and existing beans, eliminating most manual configuration work.
Common Spring Boot Starter POMs
| Starter Name | Description |
|---|---|
spring-boot-starter |
Core POM including auto-configuration support, logging libraries, and YAML configuration file support |
spring-boot-starter-amqp |
Adds AMQP messaging support via spring-rabbit |
spring-boot-starter-aop |
Includes spring-aop and AspectJ for AOP functionality |
spring-boot-starter-batch |
Adds support for Spring Batch, including embedded HSQLDB for testing |
spring-boot-starter-data-jpa |
Bundles spring-data-jpa, spring-orm, and Hibernate for JPA database access |
spring-boot-starter-data-mongodb |
Adds Spring Data MongoDB support for NoSQL MongoDB databases |
spring-boot-starter-data-rest |
Exposes Spring Data repositories as REST endpoints via spring-data-rest-webmvc |
spring-boot-starter-jdbc |
Provides support for JDBC database connectivity |
spring-boot-starter-security |
Includes Spring Security for authentication and authorization |
spring-boot-starter-test |
Bundles common testing libraries including JUnit, Hamcrest, Mockito, and spring-test |
spring-boot-starter-velocity |
Adds support for the Velocity template engine |
spring-boot-starter-web |
Enables web application development with Tomcat and Spring MVC |
spring-boot-starter-websocket |
Adds WebSocket application support using Tomcat |
spring-boot-starter-ws |
Provides support for Spring Web Services |
spring-boot-starter-actuator |
Adds production-ready features like performance metrics and monitoring |
spring-boot-starter-remote-shell |
Enables remote SSH access to the application |
spring-boot-starter-jetty |
Replaces the default Tomcat server with Jetty |
spring-boot-starter-log4j |
Adds Log4j logging framework support |
spring-boot-starter-logging |
Uses Spring Boot’s default Logback logging framework |
spring-boot-starter-tomcat |
Uses the default embedded Tomcat web server |
All starter dependencies provide a standardized, production-ready foundation for Spring applications, with curated third-party library versions tested for compatibility. Developers can also swap components, such as switching between Logback and Log4j for logging, or Tomcat and Jetty for the web server.
Spring Boot Configuration Files
Spring Boot supports .properties, .yml, and .yaml configuration files, all of which use the same set of configuration parameters sourced from dependent JARs. Changing the file type does not add or remove available parameters, as the underlying configuraton keys remain consistent.
Example Configuration
YAML Format (application.yml)
server:
port: 8080
servlet:
context-path: /squirtle
Properties Format (application.properties)
server.port=8080
server.servlet.context-path=/squirtle
Most production projects prefer YAML files due to their clear hierarchical structure and reduced redundant text compared to flat .properties files.
Custom Configuration in Spring Boot
There are two common approaches to implement custom configuration parameters:
Method 1: Simple Parameter Injection with @Value
- Define custom parameters in a YAML configuration file:
rsa: deviceLogin: userName: root password: root apiUri: /api/third-party/auth - Inject the parameters into a Spring-managed bean:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; @Service public class ThirdPartyAuthService { @Value("${rsa.deviceLogin.userName}") private String authUsername; @Value("${rsa.deviceLogin.password}") private String authPassword; @Value("${rsa.deviceLogin.apiUri}") private String apiEndpoint; }Note: The target class must be registered in the Spring application context to enable dependency injection.
Method 2: Type-Safe Configuration with @ConfigurationProperties
This method is better for complex configuration structures, as it provides type safety and cleaner code.
-
Define custom configuration parameters in a YAML file:
custom: defaultUser: "张三" sampleBean: id: 20 username: "张三" integerArray: [1, 3, 5, 7] doubleArray: [1.2, 3.4, 5.6] stringArray: - "first-item" - "second-item" stringList: - "list-item-1" - "list-item-2" simpleMap: key1: "value1" key2: "value2" nestedListMap: - id: 101 name: "employee-1" - id: 102 name: "employee-2" beanList: - id: 20 username: "zhangsan" - id: 21 username: "lisi" -
Create a type-safe configuration class:
package com.example.demo.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; @Data @Component @ConfigurationProperties(prefix = "custom") public class CustomAppConfig { private String defaultUser; private AppUser sampleBean; private int[] integerArray; private double[] doubleArray; private String[] stringArray; private List<String> stringList; private Map<String, String> simpleMap; private List<Map<String, String>> nestedListMap; private List<AppUser> beanList; // Inner POJO for nested bean configuration @Data public static class AppUser { private int id; private String username; } }Key requirements for this class:
- Field names must exactly match the configuration keys under the specified prefix
- All fields must have standard getter and setter methods (handled automatically via Lombok's
@Dataannotation) - Nested objects must have they own getter/setter methods for their properties
- The class must be annotated with
@ConfigurationPropertieswith the correct prefix, and registered in the Spring context.