AgentSkillsCN

spring-boot-patterns

Spring Boot 3 中控制器、服务、配置与校验层的最佳实践

SKILL.md
--- frontmatter
name: spring-boot-patterns
description: Spring Boot 3 patterns for controllers, services, configuration, and validation
keywords:
  - spring
  - spring-boot
  - rest
  - controller
  - service
  - repository
  - dependency injection
  - configuration
  - validation
  - actuator
  - profile
filePatterns:
  - "*.java"
  - "application.yml"
  - "application.properties"
  - "application-*.yml"
frameworks:
  - spring-boot
  - spring-framework
tokenCount: 3500
version: 1.0.0

Spring Boot Patterns

Spring Boot 3.x best practices for enterprise Java APIs. Architecture and clarity over framework tricks.

Selective Reading Rule

Read only files relevant to the request. Use the content map to focus.

Content Map

FileDescriptionWhen to Read
layered-arch.mdController -> Service -> RepositoryArchitecture design
rest-api.mdREST endpoints, DTOs, validationAPI development
configuration.md@ConfigurationProperties, profilesConfig and envs
exceptions.md@ControllerAdvice, ProblemDetailError handling
observability.mdActuator, logging, metricsProduction readiness

Core Patterns

1. Layered Architecture

code
Controller -> Service -> Repository

Keep controllers thin, services own business rules, repositories focus on data access.

2. REST Controller + DTOs

java
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
@Validated
public class UserController {

    private final UserService userService;

    @GetMapping("/{id}")
    public UserResponse findById(@PathVariable String id) {
        return userService.findById(id)
            .map(UserResponse::from)
            .orElseThrow(() -> new ResourceNotFoundException("User", id));
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public UserResponse create(@Valid @RequestBody CreateUserRequest request) {
        return UserResponse.from(userService.create(request.toCommand()));
    }
}

public record CreateUserRequest(
    @NotBlank @Email String email,
    @NotBlank @Size(min = 2, max = 100) String name
) {
    public CreateUserCommand toCommand() {
        return new CreateUserCommand(email, name);
    }
}

3. Configuration Properties

java
@ConfigurationProperties(prefix = "app")
@Validated
public record AppProperties(
    @NotBlank String name,
    @NotNull SecurityProperties security
) {
    public record SecurityProperties(
        @NotBlank String jwtSecret,
        @Positive int jwtExpirationMinutes
    ) {}
}

4. Error Handling

java
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ProblemDetail handleNotFound(ResourceNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}

Decision Checklist

  • Layered architecture respected?
  • DTOs separated from entities?
  • Validation at API boundary?
  • Exceptions centralized?
  • Config externalized?

Anti-Patterns

Anti-PatternWhy BadBetter Approach
Business logic in controllerHard to testMove to service
Field injectionHidden depsConstructor injection
Entity in responseLeaks internalsDTO pattern
open-in-view trueHidden queriesFetch explicitly

Related Skills

NeedSkill
Data access@[skills/spring-data-jpa]
Security@[skills/spring-security]
Testing@[skills/spring-testing]