java后端编程
下载地址
https://www.zhengdianxue.com/wp-content/uploads/skills/user_c11ac35d--java-sy-ml.zip将提示词发送给你的 AI 安装该 skills
请根据 https://skillhub.cn/install/skillhub.md,安装 @user_c11ac35d/java-sy-ml。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.
阅读全文 (展开查看完整说明)
概述
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-parentas 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)
| Scenario | Starter |
|---|---|
| Web/REST API | spring-boot-starter-web |
| Database (JPA) | spring-boot-starter-data-jpa |
| Database (MyBatis) | mybatis-spring-boot-starter |
| Validation | spring-boot-starter-validation |
| Security | spring-boot-starter-security |
| Redis | spring-boot-starter-data-redis |
| RabbitMQ/Kafka | spring-boot-starter-amqp / spring-kafka |
| Scheduled Tasks | spring-boot-starter-quartz |
| Actuator | spring-boot-starter-actuator |
| Test | spring-boot-starter-test |
| Lombok | lombok (scope: provided) |
| MapStruct | mapstruct (scope: provided) |
| Swagger/OpenAPI | springdoc-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.javaKey Architectural Rules
- Controller layer — Only handle HTTP concerns: parameter binding, validation, response wrapping. Never contain business logic.
- Service layer — All business logic lives here. Services are stateless and injected via
@Service. - Mapper/Repository layer — Only data access. No business logic.
- DTO separation — Never expose entity classes directly via API. Always map between entity and DTO.
- 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
@Validfor request body validation - Return unified response format:
{ "code": 200, "message": "success", "data": { ... } }- Use
@RestControllerAdvice+@ExceptionHandlerfor 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: infoMulti-Profile Setup
application-dev.yml— Local development (H2 or local MySQL)application-test.yml— Test environmentapplication-prod.yml— Production (externalized config, no hardcoded secrets)
Testing Strategy
- Unit tests for service layer using JUnit 5 + Mockito
- Integration tests for controller layer using
@WebMvcTestorMockMvc - Repository tests using
@DataJpaTestwith H2 in-memory DB - Use TestContainers for integration tests requiring real databases (MySQL, Redis, etc.)
- Test naming:
methodName_stateUnderTest_expectedBehavior(e.g.,createUser_withValidInput_returnsCreatedUser)
Common Pitfalls to Avoid
- Circular dependency — Avoid constructor injection cycles; use
@Lazyor restructure - Transaction not rolling back — Ensure
@Transactionalis on public methods - N+1 query problem — Use
@EntityGraphorJOIN FETCHin JPA; use<collection>in MyBatis - Session closed in lazy loading — Disable
spring.jpa.open-in-viewand eagerly fetch needed data - Swagger not scanning — Ensure controller package is in component scan path
- Date timezone issues — Always set
serverTimezone=Asia/Shanghaiin JDBC URL; useInstant/LocalDateTimeoverDate - 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 recipesreferences/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).