AGENTS.md – Spring Boot Backend Development
AGENTS.md – Spring Boot Backend Development进行后端功能开发时候请遵守以下规范严禁自由发挥1. Project OverviewFramework: Spring Boot 3.x (with Java 17)Build Tool: MavenPersistence: Spring Data JPA (Hibernate) MySQLConnection Pool: Druid (Alibaba) – configured viaapplication.ymlAPI Style: RESTful JSON over HTTPSecurity: Spring Security with JWT (or OAuth2)Documentation: OpenAPI 3 (springdoc-openapi)Testing: JUnit 5, Mockito, Spring Boot Test, Testcontainers (MySQL)Logging: SLF4J LogbackCaching: Spring Cache (optional)2. Project Structure (Maven layout)src/ ├── main/ │ ├── java/com/example/app/ │ │ ├── AppApplication.java # Main class │ │ ├── config/ # Configuration classes (including DruidConfig) │ │ ├── controller/ # REST controllers (e.g., UserController) │ │ ├── service/ # Business logic interfaces implementations │ │ ├── repository/ # Spring Data JPA repositories │ │ ├── model/entity/ # JPA entities (e.g., User, Order) │ │ ├── model/dto/ # Data Transfer Objects (request/response) │ │ ├── mapper/ # MapStruct or manual mappers │ │ ├── exception/ # Custom exceptions and global handlers │ │ ├── security/ # Security config, filters, JWT utils │ │ ├── util/ # Utility classes │ │ └── validation/ # Custom validators │ └── resources/ │ ├── application.yml # Main configuration (profile: dev) │ ├── application-prod.yml │ ├── db/migration/ # Flyway/Liquibase scripts (if used) │ └── static/ # (if any) └── test/ ├── java/com/example/app/ │ ├── controller/ # Web layer tests (WebMvcTest) │ ├── service/ # Unit tests with Mockito │ └── repository/ # Data layer tests (DataJpaTest) └── resources/ └── application-test.yml3. Coding Conventions3.1. NamingClasses: PascalCase, singular nouns (e.g.,UserService,OrderRepository).Interfaces: UseIprefix?No– standard Java naming:UserService(interface),UserServiceImpl(implementation).Methods: camelCase, verbs (e.g.,findById,createOrder).Constants: UPPER_SNAKE_CASE.Packages: all lowercase, dot-separated.3.2. Annotations PatternsUseLombokto reduce boilerplate:Data,Builder,AllArgsConstructor,NoArgsConstructor,Slf4j.Preferconstructor injectionover field injection for better testability.UseTransactionalat the service layer for database operations.For DTOs, useValidwith Jakarta Bean Validation (NotNull,Size, etc.).3.3. REST API DesignUse plural nouns for resources:/api/users,/api/orders.HTTP methods: GET, POST, PUT, PATCH, DELETE.Return appropriate status codes (200, 201, 400, 404, 422, 500).Always useResponseEntityto wrap responses.3.4. Exception HandlingCreate a globalControllerAdvicethat handles:MethodArgumentNotValidException→ 400 Bad RequestEntityNotFoundException(custom) → 404 Not FoundAccessDeniedException→ 403 ForbiddenRuntimeException→ 500 Internal Server ErrorReturn a consistent error payload:{ timestamp, status, error, message, path }.3.5. LoggingUseSlf4jand log at appropriate levels:INFOfor significant events (startup, successful operations).DEBUGfor detailed flow (e.g., SQL parameters, method entry/exit).WARNfor recoverable issues.ERRORfor exceptions caught by global handler.Never log sensitive data (passwords, tokens).4. Development Workflow4.1. Setting Up Local EnvironmentInstall JDK 17, Maven, Docker (optional for MySQL).Create a MySQL database (e.g.,app_db).Adjustapplication.ymlspring.datasourcesettings (see Section 6).Run database migrations (Flyway/Liquibase) on startup (enabled by default).4.2. Adding a New FeatureDefine the entity– inmodel/entity/with JPA annotations.Create repository– extendJpaRepositoryT, ID.Create DTOs– request and response objects inmodel/dto/.Write service interface and implementation– business logic, using repository.Create controller– map endpoints, useValidon request bodies.Add validation annotationson DTO fields.Write unit testsfor service and repository layers.Update OpenAPI documentation(if usingspringdoc).4.3. Database MigrationsUse Flyway (or Liquibase) scripts indb/migration/.Version files:V1__initial_schema.sql,V2__add_created_at.sql.Ensure SQL syntax is MySQL-compatible.Never modify existing scripts; create new versions.4.4. Testing StrategyUnit Tests– for service classes with mocked repositories.Integration Tests– withSpringBootTestand Testcontainers for MySQL.Web Slice Tests–WebMvcTestfor controller layer.Data Slice Tests–DataJpaTestfor repository queries.Aim for 80% coverage on critical business logic.5. Security GuidelinesUseSpring Securitywith JWT.Secure endpoints withPreAuthorizeorSecuredannotations.Store passwords usingBCryptPasswordEncoder.Never expose sensitive fields in DTOs (e.g., password).Validate JWT token via a filter (once-per-request).6. Configuration ManagementUseapplication.ymlfor default settings.Environment-specific overrides:application-dev.yml,application-prod.yml.UseConfigurationPropertiesfor grouping external config (e.g.,app.jwt.secret).Druid Connection Pool ConfigurationAdd the following toapplication.yml:spring:datasource:driver-class-name:com.mysql.cj.jdbc.Driverurl:jdbc:mysql://localhost:3306/app_db?useSSLfalseserverTimezoneUTCallowPublicKeyRetrievaltrueusername:rootpassword:yourpasswordtype:com.alibaba.druid.pool.DruidDataSourcedruid:# Initial connection pool sizeinitial-size:5# Minimum idle connectionsmin-idle:5# Maximum active connectionsmax-active:20# Connection timeout (ms)max-wait:60000# Time between eviction checks (ms)time-between-eviction-runs-millis:60000# Minimum evictable idle time (ms)min-evictable-idle-time-millis:300000# Validation queryvalidation-query:SELECT 1# Test while idletest-while-idle:true# Test on borrow (false recommended)test-on-borrow:false# Test on return (false recommended)test-on-return:false# Enable PoolPreparedStatementspool-prepared-statements:truemax-pool-prepared-statement-per-connection-size:20# Filter configuration (optional)filters:stat,wall# WebStatFilter (for monitoring)web-stat-filter:enabled:trueurl-pattern:/*exclusions:*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*# StatViewServlet (for Druid console)stat-view-servlet:enabled:trueurl-pattern:/druid/*login-username:adminlogin-password:admin123reset-enable:falseNote: You may also configure Druid via a separateConfigurationclass if you need more advanced settings.7. Build Run CommandsBuild:mvn clean packageRun:mvn spring-boot:runTests:mvn test(with profiles)Docker:docker build -t app .(if Dockerfile exists)8. Code QualityUseSonarQubeorSpotBugsfor static analysis.Format code withGoogle Java Style(or usespotlessplugin).AvoidSystem.out.println; use logging.9. AI Agent Specific InstructionsWhen generating or suggesting code, please adhere to the following:Generate complete code blockswith proper imports and package declarations.Always include exception handlingfor repository/service calls.UseAutowiredonly when constructor injection is impractical; prefer constructor injection.When writing REST endpoints, provide OpenAPI annotations (Operation,ApiResponse) for automatic docs.For new DTOs, includeSchemaannotations for OpenAPI.Write test classesfor every new service/controller, using given-when-then style.PreferStreamAPIfor collection processing.UseOptionalfor nullable return types (e.g., from repository find methods).Avoid usingnull; useOptionalor throw appropriate exception.For pagination, use Spring’sPageableand returnPageT.When interacting with external APIs, useRestClientorWebClientwith timeout and retry.10. Useful Dependencies (Maven)Add the following to yourpom.xml:dependencies!-- Spring Boot Starters --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-data-jpa/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-security/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-validation/artifactId/dependencydependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-cache/artifactId/dependency!-- MySQL Driver --dependencygroupIdcom.mysql/groupIdartifactIdmysql-connector-j/artifactIdscoperuntime/scope/dependency!-- Druid Connection Pool --dependencygroupIdcom.alibaba/groupIdartifactIddruid-spring-boot-3-starter/artifactIdversion1.2.23/version/dependency!-- Database Migration (Flyway) --dependencygroupIdorg.flywaydb/groupIdartifactIdflyway-core/artifactId/dependencydependencygroupIdorg.flywaydb/groupIdartifactIdflyway-mysql/artifactId/dependency!-- OpenAPI / Swagger --dependencygroupIdorg.springdoc/groupIdartifactIdspringdoc-openapi-starter-webmvc-ui/artifactIdversion2.5.0/version/dependency!-- JWT --dependencygroupIdio.jsonwebtoken/groupIdartifactIdjjwt-api/artifactIdversion0.12.5/version/dependencydependencygroupIdio.jsonwebtoken/groupIdartifactIdjjwt-impl/artifactIdversion0.12.5/versionscoperuntime/scope/dependencydependencygroupIdio.jsonwebtoken/groupIdartifactIdjjwt-jackson/artifactIdversion0.12.5/versionscoperuntime/scope/dependency!-- Lombok --dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdoptionaltrue/optional/dependency!-- Test --dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.springframework.security/groupIdartifactIdspring-security-test/artifactIdscopetest/scope/dependencydependencygroupIdorg.testcontainers/groupIdartifactIdtestcontainers/artifactIdversion1.19.8/versionscopetest/scope/dependencydependencygroupIdorg.testcontainers/groupIdartifactIdmysql/artifactIdversion1.19.8/versionscopetest/scope/dependency/dependenciesVersion notes: Adjust versions as needed. Thedruid-spring-boot-3-starteris compatible with Spring Boot 3.x.11. Common Pitfalls to AvoidDo not expose internal entity objects directly in API responses (use DTOs).Avoid lazy loading exceptions; useTransactionalor fetch joins.Do not injectHttpServletRequestin service layer.Avoid tight coupling between packages; follow hexagonal/clean architecture if applicable.Do not ignoreValidon request body; always validate input.Ensure MySQL timezone and SSL settings match your environment.Druid filters (stat, wall) are optional but recommended for monitoring and SQL injection protection.12. Final NotesAlways run tests locally before pushing.For any major change, update theREADME.mdand AGENTS.md accordingly.Feel free to ask clarifying questions if requirements are ambiguous.最后再次说明进行后端功能开发时候请遵守以上规范严禁自由发挥

相关新闻

Unity自动滚动文本框实现:RectTransform动画与UGUI动态布局

Unity自动滚动文本框实现:RectTransform动画与UGUI动态布局

1. 项目概述:为什么我们需要一个“会自己动”的文本框?在Unity UI开发里,处理大段文本是家常便饭。无论是游戏里的任务日志、剧情旁白,还是应用中的公告、聊天记录,我们经常遇到一个经典难题:文本内容超出了…

2026/7/31 12:05:19 阅读更多
智慧园区照明监控与能源管理系统方案

智慧园区照明监控与能源管理系统方案

某大型产业园区拟部署一套智慧照明与能源管理系统,覆盖公共道路、广场、停车场、楼宇外围等公共区域照明,以及入驻企业的用电能耗监测。公共区域照明采用群控策略,实现按时间段、光照强度自动调节开关与亮度;企业端则重点监测能耗…

2026/7/31 12:05:19 阅读更多
手机数码租赁小程序前端设计与性能优化实战

手机数码租赁小程序前端设计与性能优化实战

1. 项目概述:手机数码租赁小程序的前端功能设计作为一名经历过多个租赁类项目开发的前端工程师,我深刻理解这类产品的核心痛点——如何在有限的界面空间内,既要展示丰富的商品信息,又要保证租赁流程的顺畅。这次我们开发的数码租赁…

2026/7/31 12:05:19 阅读更多
Obsidian插件汉化终极指南:3步打造全中文笔记工作流

Obsidian插件汉化终极指南:3步打造全中文笔记工作流

Obsidian插件汉化终极指南:3步打造全中文笔记工作流 【免费下载链接】obsidian-i18n 项目地址: https://gitcode.com/gh_mirrors/ob/obsidian-i18n 还在为Obsidian插件中的英文界面而烦恼吗?obsidian-i18n是一款专为Obsidian设计的智能本地化工具…

2026/7/31 14:05:23 阅读更多
程序员简历的另外三个优化点

程序员简历的另外三个优化点

关于程序员简历,我之前已经写过不少内容,比如项目经历怎么写、技术亮点怎么写等等。 今天这篇再补充三个细节。 第一,技能项不要列太多,且最好归类 很多人的技能那一栏是这样写的:Java、Spring Boot、Spring Cloud、My…

2026/7/31 14:05:23 阅读更多
HART协议详解:05 HART现场通信实战

HART协议详解:05 HART现场通信实战

第五季 HART现场通信实战 ——从USB-HART Modem抓包到工程诊断:让协议知识变成维修能力 各位工业现场的工程师朋友们,大家好! 经过前四季的系统学习,我们已经构建了HART协议的完整理论框架: 第一季:六层生命模型与本质认知 第二季:物理层4–20mA与FSK魔法 第三季:数…

2026/7/31 0:14:40 阅读更多
维修工程师的示波器实战:02 探头地线——示波器最大的“坑”

维修工程师的示波器实战:02 探头地线——示波器最大的“坑”

第二篇:探头地线——示波器最大的“坑” ——那根不起眼的小地线,可能比你测的信号还重要 很多工程师第一次用示波器时,都会经历这样一个“惊魂”时刻。 某食品厂包装线,伺服偶发报警。年轻工程师判断是编码器信号受干扰,便拿出示波器认真测量。波形一出来,所有人都倒…

2026/7/31 0:14:40 阅读更多