Essential Guide to Spring Boot Fundamentals
Spring Boot accelerates Spring application development by simplifying configuration and providing out-of-the-box features. This guide covers the core concepts to get started.
1. Creating a Spring Boot Project
Using an IDE like IntelliJ IDEA, select New Project, choose Spring Initializr as the generator, and Maven as the type. Add dependencies such as Spring Web during setup.
A typical project structure is generated:
myapp
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ └── myapp
│ │ │ └── MyappApplication.java
│ │ └── resources
│ │ └── application.properties
└── pom.xml
Maven manages dependencies via the pom.xml file, reducing the complexity of manual imports.
2. Managing Dependencies
Dependencies are added to the pom.xml file within the <dependencies> section. Refresh the project to apply changes.
2.1 Common Dependencies
-
MySQL Connector/J: The official JDBC driver for connecting Java applications to MySQL databases.
-
Spring Boot Starter JDBC: Simplifies JDBC database connection configuration. Database connection details are set in
application.properties:spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=dbuser spring.datasource.password=dbpass spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver -
Project Lombok: Reduces boilerplate code (like getters, setters, constructors) in POJO classes via annotations.
-
MyBatis-Plus Dependencies (
mybatis-plus-boot-starter,mybatis-plus-generator): Provides generic Mapper interfaces for CRUD operations, minimizign SQL writing. Themybatis-springdependency may be needed for integration. -
Spring Boot Starter Security: Adds authentication and authorization capabilities. Note: Adding this will require login for web access.
3. Application Layers and Responsibilities
The standard layered architecture includes:
- POJO Layer: Defines data objects.
- Mapper Layer: Handles database interactions.
- Service Layer: Contains business logic.
- Controller Layer: Manages HTTP requests and responses.
Create corresponding packages (pojo, mapper, service, controller) under the main applicasion package.
3.1 POJO (Plain Old Java Object)
The class name often matches the database table name, and fields correspond to table columns. Lombok annotations automate method generation.
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Customer {
private Long customerId;
private String name;
private String emailAddress;
// Getters, setters, toString, etc., are generated by Lombok
}
3.2 Mapper
This interface defines database operations. MyBatis-Plus provides base interfaces to extend.
@Mapper
public interface CustomerMapper {
@Select("SELECT * FROM customers WHERE customer_id = #{id}")
Customer selectCustomerById(Long id);
// Other data access methods
}
3.3 Service
The service class implements business logic by calling mapper methods.
@Service
public class CustomerService {
@Autowired
private CustomerMapper customerMapper;
public Customer fetchCustomerById(Long id) {
return customerMapper.selectCustomerById(id);
}
// Additional business methods
}
3.4 Controller
Controllers handle HTTP requests, invoke services, and return responses (e.g., JSON).
@RestController
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping("/customers/{id}")
public Customer getCustomer(@PathVariable Long id) {
return customerService.fetchCustomerById(id);
}
// Other endpoint handlers
}
4. Embedded Server
Spring Boot includes a web server (Tomcat by default) within the application JAR. This allows the app to run independently via java -jar, simplifying deployment. The server can be switched (e.g., to Jetty) by changing dependencies in pom.xml.
5. Externalized Configuration
Configuration is separated from code using property or YAML files, enabling environment-specific settings.
5.1 application.properties
Uses a key-value format.
server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/testdb
logging.level.root=INFO
5.2 application.yml
Uses YAML's hierarchical structure.
server:
port: 8080
spring:
datasource:
url: jdbc:mysql://localhost:3306/testdb
logging:
level:
root: INFO
Configuration sources are loaded in this order (later sources override earlier ones):
application.properties/application.ymlfromsrc/main/resources.- Command-line arguments (e.g.,
--server.port=8081). - Environment variables.
6. Spring Security Basics
Adding the Spring Security starter enables authentication. A common pattern is JWT (JSON Web Token) based authentication.
6.1 JWT Authentication Flow
- Client sends login credentials.
- Server validates credentials and generates a JWT using a secret key and user info.
- The JWT is returned to the client.
- Subsequent client requests include the JWT in the header.
- Server validates the JWT for each request.
6.2 Key Security Components
UsernamePasswordAuthenticationToken: Carries user credentials for authentication.UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);AuthenticationManager: Core interface for performing authentication.Authentication authResult = authenticationManager.authenticate(authRequest);UserDetails/UserDetailsImpl: Interface and implementation holding authenticated user details.UserDetailsImpl principal = (UserDetailsImpl) authResult.getPrincipal(); User currentUser = principal.getUser();PasswordEncoder: Encodes and verifies passwords.String encryptedPwd = passwordEncoder.encode(plainTextPassword); boolean matches = passwordEncoder.matches(plainTextPassword, storedEncryptedPwd);SecurityContextHolder: Provides access to the current security context and authenticated user.Authentication auth = SecurityContextHolder.getContext().getAuthentication(); UserDetailsImpl userDetails = (UserDetailsImpl) auth.getPrincipal();- Custom Classes:
JwtUtil(for creating/parsing tokens),JwtAuthenticationTokenFilter(for request filtering), andSecurityConfig(for security configuration) are typically implemented as needed.