Java SpringBoot Framework

Java 常用类库Common Java Libraries


SpringBoot is an extension project of the Spring framework, aimed at simplifying the initial setup and development process of Spring applications.

SpringBoot enables developers to quickly start and run Spring applications through the "convention over configuration" philosophy.

Core Features of SpringBoot

  1. Auto-configuration: Automatically configures Spring applications based on the jar dependencies added to the project.
  2. Standalone: Embedded Tomcat, Jetty, or Undertow servers, no need to deploy WAR files.
  3. Simplified Dependency Management: Simplifies Maven/Gradle configuration through starter dependencies.
  4. Production-Ready: Provides metrics, health checks, externalized configuration, and other features.
  5. No Code Generation: No XML configuration required.

Core Components of SpringBoot

1. SpringBoot Starter

SpringBoot Starter is a set of convenient dependency descriptors that let you obtain all the technologies you need in one stop. For example:

  • spring-boot-starter-web: Used to build web applications.
  • spring-boot-starter-data-jpa: Used for JPA database access.
  • spring-boot-starter-test: Used for testing.

2. SpringBoot AutoConfiguration

SpringBoot automatically configures the application based on the jar packages in the classpath. For example, if the H2 database is in the classpath, SpringBoot will automatically configure an in-memory database.

3. SpringBoot Actuator

Provides production-grade features to help monitor and manage applications:

  • Application health checks
  • Metrics collection
  • HTTP tracing
  • Environment information

Create Your First SpringBoot Application

1. Create a Project Using Spring Initializr

Visitstart.spring.io, select:

  • Maven Project
  • Java Language
  • Latest SpringBoot version
  • Add the "Web" dependency

2. Project Structure

Typical SpringBoot project structure:

src/
  main/
    java/
      com/example/demo/
        DemoApplication.java   # 主启动类
    resources/
      application.properties  # 配置文件
  test/
    java/
      com/example/demo/
        DemoApplicationTests.java # 测试类

3. Write a Simple REST Controller

Example

@RestController
@RequestMapping("/api")
public class HelloController {

    @GetMapping("/hello")
    public String sayHello() {
        return "Hello, SpringBoot!";
    }
}

4. Run the Application

RunDemoApplicationmethod in the classmain, the application will start on the default port 8080.

Visithttp://localhost:8080/api/hellowill see the returned "Hello, SpringBoot!" message.


SpringBoot Configuration

1. Configuration Files

SpringBoot supports multiple configuration methods:

  • application.properties
  • application.yml
  • Environment variables
  • Command line arguments

Exampleapplication.properties:

Example

server.port=9090
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret

2. Multi-Environment Configuration

You can create different configuration files for different environments:

  • application-dev.properties: Development environment
  • application-prod.properties: Production environment

Specify the active environment viaspring.profiles.active:

Example

spring.profiles.active=dev

SpringBoot Data Access

1. Using Spring Data JPA

Add dependency:

Example

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

Define entity class:

Example

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String email;
    // getters and setters
}

Create Repository interface:

Example

public interface UserRepository extends JpaRepository<User, Long> {
    List<User> findByName(String name);
}

Use in the service layer:

Example

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
   
    public List<User> getUsersByName(String name) {
        return userRepository.findByName(name);
    }
}

SpringBoot Best Practices

  1. Layered Architecture: Follow the Controller-Service-Repository layering
  2. Exception Handling: Use@ControllerAdviceglobal exception handling
  3. Logging: Use SLF4J for logging
  4. Unit Testing: Write sufficient tests for business logic
  5. API Documentation: Integrate Swagger to generate API documentation

Example: Global Exception Handling

Example

@ControllerAdvice
public class GlobalExceptionHandler {
   
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
        ErrorResponse error = new ErrorResponse(
            "NOT_FOUND",
            ex.getMessage()
        );
        return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
    }
}

SpringBoot Advanced Topics

  1. Spring Security: Authentication and authorization
  2. Spring Cloud: Microservices architecture
  3. Spring Batch: Batch processing
  4. WebFlux: Reactive programming
  5. Docker Integration: Containerized deployment

SpringBoot greatly improves the development efficiency of Java applications by simplifying configuration and providing out-of-the-box features. It is one of the indispensable frameworks in modern Java development.

Java 常用类库Common Java Libraries

Other Extensions