Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Guide to Spring Boot Fundamentals

Tech 2

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

  1. MySQL Connector/J: The official JDBC driver for connecting Java applications to MySQL databases.

  2. 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
    
  3. Project Lombok: Reduces boilerplate code (like getters, setters, constructors) in POJO classes via annotations.

  4. MyBatis-Plus Dependencies (mybatis-plus-boot-starter, mybatis-plus-generator): Provides generic Mapper interfaces for CRUD operations, minimizign SQL writing. The mybatis-spring dependency may be needed for integration.

  5. 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):

  1. application.properties / application.yml from src/main/resources.
  2. Command-line arguments (e.g., --server.port=8081).
  3. 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

  1. Client sends login credentials.
  2. Server validates credentials and generates a JWT using a secret key and user info.
  3. The JWT is returned to the client.
  4. Subsequent client requests include the JWT in the header.
  5. 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), and SecurityConfig (for security configuration) are typically implemented as needed.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.