← 返回
未分类

java后端编程

Specialized skill for Java Spring Boot backend development. This skill should be used when users ask to build REST APIs, create Spring Boot projects, write Java backend services, configure database access (JPA/MyBatis), handle authentication (Spring Security/JWT), implement microservices (Spring Cloud), troubleshoot Spring Boot errors, review Java code quality, or perform any Spring Boot / Java backend related task.
Specialized skill for Java Spring Boot backend development. This skill should be used when users ask to build REST APIs, create Spring Boot projects, write Java backend services, configure database access (JPA/MyBatis), handle authentication (Spring Security/JWT), implement microservices (Spring Cloud), troubleshoot Spring Boot errors, review Java code quality, or perform any Spring Boot / Java backend related task.
user_c11ac35d
未分类 community v1.0.0 1 版本 100000 Key: 无需
★ 0
Stars
📥 103
下载
💾 0
安装
1
版本
#latest

概述

Java Spring Boot Backend Development

A specialized skill for building production-grade Java Spring Boot backend services.

Trigger Conditions

Activate this skill when user intent involves:

  • Building/creating Spring Boot projects or applications
  • Writing REST APIs, controllers, services, or repositories
  • Configuring database access (Spring Data JPA, MyBatis, MyBatis-Plus)
  • Implementing authentication/authorization (Spring Security, JWT, OAuth2)
  • Microservice architecture (Spring Cloud, Nacos, Feign, Gateway)
  • Java code review, refactoring, or performance optimization
  • Debugging Spring Boot startup errors, dependency conflicts, or runtime issues
  • Writing unit/integration tests (JUnit 5, Mockito, TestContainers)
  • Deploying Spring Boot apps (Docker, K8s, CI/CD)

Technology Stack Preferences

Build Tools

  • Maven preferred over Gradle unless user specifies otherwise
  • Use spring-boot-starter-parent as parent POM
  • Follow standard Maven directory structure

Java Version

  • Default to Java 17 LTS unless user specifies otherwise (Java 8, 11, 21 also supported)

Key Dependencies (Common Starters)

ScenarioStarter
-------------------
Web/REST APIspring-boot-starter-web
Database (JPA)spring-boot-starter-data-jpa
Database (MyBatis)mybatis-spring-boot-starter
Validationspring-boot-starter-validation
Securityspring-boot-starter-security
Redisspring-boot-starter-data-redis
RabbitMQ/Kafkaspring-boot-starter-amqp / spring-kafka
Scheduled Tasksspring-boot-starter-quartz
Actuatorspring-boot-starter-actuator
Testspring-boot-starter-test
Lomboklombok (scope: provided)
MapStructmapstruct (scope: provided)
Swagger/OpenAPIspringdoc-openapi-starter-webmvc-ui

Database Conventions

  • MySQL preferred for relational DB; PostgreSQL if user specifies
  • MyBatis-Plus recommended over plain MyBatis for simpler CRUD
  • When using JPA, prefer derived queries over @Query for simple cases
  • Always configure connection pool (HikariCP is default, just tune it)
  • Use Flyway or Liquibase for schema migration in production

Project Architecture

Follow a layered architecture with clear separation of concerns:

src/main/java/com/example/project/
├── controller/      # REST endpoints, request/response DTOs
├── service/         # Business logic interfaces
│   └── impl/        # Service implementations
├── mapper/          # Data access layer (MyBatis) or repository/ (JPA)
├── entity/          # Database entity classes
├── dto/             # Data Transfer Objects
│   ├── request/     # Incoming request DTOs
│   └── response/    # Outgoing response DTOs
├── config/          # Configuration classes
├── common/          # Shared utilities, constants, enums
│   ├── exception/   # Custom exceptions & global handler
│   ├── result/      # Unified API response wrapper
│   └── util/        # Utility classes
└── Application.java

Key Architectural Rules

  1. Controller layer — Only handle HTTP concerns: parameter binding, validation, response wrapping. Never contain business logic.
  2. Service layer — All business logic lives here. Services are stateless and injected via @Service.
  3. Mapper/Repository layer — Only data access. No business logic.
  4. DTO separation — Never expose entity classes directly via API. Always map between entity and DTO.
  5. Use MapStruct for entity-DTO mapping when fields are non-trivial. Manual mapping for simple cases.

Coding Standards

Naming Conventions

  • Controller: XxxController
  • Service interface: XxxService
  • Service impl: XxxServiceImpl
  • Mapper: XxxMapper
  • Entity: Xxx (singular noun, matches table name in snake_case)
  • DTO: XxxRequest, XxxResponse, XxxDTO

API Design

  • Follow RESTful conventions (proper HTTP methods, resource naming)
  • Use @Valid for request body validation
  • Return unified response format:

```json

{ "code": 200, "message": "success", "data": { ... } }

```

  • Use @RestControllerAdvice + @ExceptionHandler for global error handling
  • Paginate list APIs with Pageable (Spring Data) or custom pagination DTO

Error Handling

  • Define custom business exceptions extending RuntimeException
  • Global exception handler catches all exceptions and returns structured response
  • Log errors with proper level (ERROR for unexpected, WARN for business violations)

Logging

  • Use SLF4J via Lombok @Slf4j
  • Log at appropriate levels: ERROR (exceptions), WARN (business rule violations), INFO (key business events), DEBUG (development details)
  • Never log sensitive data (passwords, tokens, PII)

Configuration Best Practices

application.yml Structure

server:
  port: 8080

spring:
  profiles:
    active: dev
  datasource:
    url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: ${DB_USERNAME}
    password: ${DB_PASSWORD}
    driver-class-name: com.mysql.cj.jdbc.Driver
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5
  jpa:
    hibernate:
      ddl-auto: validate
    show-sql: false
    open-in-view: false

mybatis-plus:
  mapper-locations: classpath*:mapper/**/*.xml
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

logging:
  level:
    com.example.project: info

Multi-Profile Setup

  • application-dev.yml — Local development (H2 or local MySQL)
  • application-test.yml — Test environment
  • application-prod.yml — Production (externalized config, no hardcoded secrets)

Testing Strategy

  1. Unit tests for service layer using JUnit 5 + Mockito
  2. Integration tests for controller layer using @WebMvcTest or MockMvc
  3. Repository tests using @DataJpaTest with H2 in-memory DB
  4. Use TestContainers for integration tests requiring real databases (MySQL, Redis, etc.)
  5. Test naming: methodName_stateUnderTest_expectedBehavior (e.g., createUser_withValidInput_returnsCreatedUser)

Common Pitfalls to Avoid

  1. Circular dependency — Avoid constructor injection cycles; use @Lazy or restructure
  2. Transaction not rolling back — Ensure @Transactional is on public methods
  3. N+1 query problem — Use @EntityGraph or JOIN FETCH in JPA; use in MyBatis
  4. Session closed in lazy loading — Disable spring.jpa.open-in-view and eagerly fetch needed data
  5. Swagger not scanning — Ensure controller package is in component scan path
  6. Date timezone issues — Always set serverTimezone=Asia/Shanghai in JDBC URL; use Instant/LocalDateTime over Date
  7. Docker image size — Use multi-stage builds; avoid unnecessary layers

Reference Materials

Detailed reference documents are available in the references/ directory:

  • references/spring-boot-common-patterns.md — Common code patterns and recipes
  • references/troubleshooting.md — Frequently encountered errors and solutions

Load these files when relevant to the current task (e.g., when debugging or implementing a specific pattern).

版本历史

共 1 个版本

  • v1.0.0 Initial release 当前
    2026-05-17 17:34 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 197 📥 67,981
dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 76 📥 182,509
dev-programming

YouTube

byungkyu
使用托管OAuth集成YouTube Data API,支持搜索视频、管理播放列表、获取频道数据及评论互动,适用于用户需要时使用此技能。
★ 142 📥 41,906