java-spring-boot

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Java Spring Boot Skill

Java Spring Boot 技能

Build production-ready Spring Boot applications with modern best practices.
使用现代最佳实践构建生产级Spring Boot应用程序。

Overview

概述

This skill covers Spring Boot development including REST APIs, security configuration, data access, actuator monitoring, and cloud integration. Follows Spring Boot 3.x patterns with emphasis on production readiness.
本技能涵盖Spring Boot开发的各个方面,包括REST API、安全配置、数据访问、Actuator监控以及云集成。遵循Spring Boot 3.x模式,重点关注生产就绪性。

When to Use This Skill

何时使用本技能

Use when you need to:
  • Create REST APIs with Spring MVC/WebFlux
  • Configure Spring Security (OAuth2, JWT)
  • Set up database access with Spring Data
  • Enable monitoring with Actuator
  • Integrate with Spring Cloud
当你需要以下操作时使用:
  • 使用Spring MVC/WebFlux创建REST API
  • 配置Spring Security(OAuth2、JWT)
  • 通过Spring Data设置数据库访问
  • 启用Actuator监控
  • 与Spring Cloud集成

Topics Covered

涵盖主题

Spring Boot Core

Spring Boot 核心

  • Auto-configuration and starters
  • Application properties and profiles
  • Bean lifecycle and configuration
  • DevTools and hot reload
  • 自动配置(Auto-configuration)与启动器(starters)
  • 应用属性与配置文件(profiles)
  • Bean生命周期与配置
  • DevTools与热重载

REST API Development

REST API 开发

  • @RestController and @RequestMapping
  • Request/response handling
  • Validation with Bean Validation
  • Exception handling with @ControllerAdvice
  • @RestController与@RequestMapping
  • 请求/响应处理
  • 基于Bean Validation的验证
  • 使用@ControllerAdvice处理异常

Spring Security

Spring Security

  • SecurityFilterChain configuration
  • OAuth2 and JWT authentication
  • Method security (@PreAuthorize)
  • CORS and CSRF configuration
  • SecurityFilterChain配置
  • OAuth2与JWT认证
  • 方法安全(@PreAuthorize)
  • CORS与CSRF配置

Spring Data JPA

Spring Data JPA

  • Repository pattern
  • Query methods and @Query
  • Pagination and sorting
  • Auditing and transactions
  • 仓库模式(Repository pattern)
  • 查询方法与@Query
  • 分页与排序
  • 审计与事务

Actuator & Monitoring

Actuator 与监控

  • Health checks and probes
  • Metrics with Micrometer
  • Custom endpoints
  • Prometheus integration
  • 健康检查与探针
  • 基于Micrometer的指标
  • 自定义端点
  • Prometheus集成

Quick Reference

快速参考

java
// REST Controller
@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody UserRequest request) {
        User user = userService.create(request);
        URI location = URI.create("/api/users/" + user.getId());
        return ResponseEntity.created(location).body(user);
    }
}

// Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .build();
    }
}

// Exception Handler
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EntityNotFoundException.class)
    public ProblemDetail handleNotFound(EntityNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage());
    }
}
java
// REST Controller
@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {

    @GetMapping("/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        return userService.findById(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping
    public ResponseEntity<User> createUser(@Valid @RequestBody UserRequest request) {
        User user = userService.create(request);
        URI location = URI.create("/api/users/" + user.getId());
        return ResponseEntity.created(location).body(user);
    }
}

// Security Configuration
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health/**").permitAll()
                .requestMatchers("/api/public/**").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
            .build();
    }
}

// Exception Handler
@RestControllerAdvice
public class GlobalExceptionHandler {

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

Configuration Templates

配置模板

yaml
undefined
yaml
undefined

application.yml

application.yml

spring: application: name: ${APP_NAME:my-service} profiles: active: ${SPRING_PROFILES_ACTIVE:local} jpa: open-in-view: false properties: hibernate: jdbc.batch_size: 50
management: endpoints: web: exposure: include: health,info,metrics,prometheus endpoint: health: probes: enabled: true
server: error: include-stacktrace: never
undefined
spring: application: name: ${APP_NAME:my-service} profiles: active: ${SPRING_PROFILES_ACTIVE:local} jpa: open-in-view: false properties: hibernate: jdbc.batch_size: 50
management: endpoints: web: exposure: include: health,info,metrics,prometheus endpoint: health: probes: enabled: true
server: error: include-stacktrace: never
undefined

Common Patterns

常见模式

Layer Architecture

分层架构

Controller → Service → Repository → Database
     ↓           ↓          ↓
   DTOs      Entities    Entities
Controller → Service → Repository → Database
     ↓           ↓          ↓
   DTOs      Entities    Entities

Validation Patterns

验证模式

java
public record CreateUserRequest(
    @NotBlank @Size(max = 100) String name,
    @Email @NotBlank String email,
    @NotNull @Min(18) Integer age
) {}
java
public record CreateUserRequest(
    @NotBlank @Size(max = 100) String name,
    @Email @NotBlank String email,
    @NotNull @Min(18) Integer age
) {}

Troubleshooting

故障排查

Common Issues

常见问题

ProblemCauseSolution
Bean not foundMissing @ComponentAdd annotation or @Bean
Circular dependencyConstructor injectionUse @Lazy or refactor
401 UnauthorizedSecurity configCheck permitAll paths
Slow startupHeavy auto-configExclude unused starters
问题原因解决方案
Bean未找到缺少@Component添加注解或@Bean
循环依赖构造函数注入使用@Lazy或重构
401未授权安全配置问题检查permitAll路径
启动缓慢繁重的自动配置排除未使用的启动器

Debug Properties

调试属性

properties
debug=true
logging.level.org.springframework.security=DEBUG
spring.jpa.show-sql=true
properties
debug=true
logging.level.org.springframework.security=DEBUG
spring.jpa.show-sql=true

Debug Checklist

调试检查清单

□ Check /actuator/conditions
□ Verify active profiles
□ Review security filter chain
□ Check bean definitions
□ Test health endpoints
□ 检查/actuator/conditions
□ 验证激活的配置文件
□ 审查安全过滤器链
□ 检查Bean定义
□ 测试健康端点

Usage

使用方法

Skill("java-spring-boot")
Skill("java-spring-boot")

Related Skills

相关技能

  • java-testing
    - Spring test patterns
  • java-jpa-hibernate
    - Data access
  • java-testing
    - Spring测试模式
  • java-jpa-hibernate
    - 数据访问