尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
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.最后再次说明进行后端功能开发时候请遵守以上规范严禁自由发挥
RELATED

相关推荐

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

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

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

📅 2026/9/9 19:40:46
智慧园区照明监控与能源管理系统方案

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

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

📅 2026/8/24 15:14:11
【梯级水电】混合式抽水蓄能+梯级水电+源网荷储研究(Matlab代码实现)

【梯级水电】混合式抽水蓄能+梯级水电+源网荷储研究(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 &#x1f381…

📅 2026/8/24 15:14:12
MORE NEWS

更多资讯

📰

CivitAI 的 `dbRead`/`dbWrite` 双客户端路由:当服务层在运行时选择数据库客户端时,测试 mock 如何正确拆分

CivitAI 的 dbRead/dbWrite 双客户端路由:当服务层在运行时选择数据库客户端时,测试 mock 如何正确拆分 【免费下载链接】civitai A repository of models, textual inversions, and more 项目地址: https://gitcode.com/GitHub_Trending/ci/civitai …

📰

2026年硕博新生报到须知及新生入校相关注意事项汇总

作为研究生,我们的科研工作不仅包括实验、数据采集和分析,还涉及大量的论文写作。在这个过程中,如何高效地处理数据、优化写作和确保研究结果的准确性,往往决定了研究的质量和效率。幸运的是,现代科技为我们提供了各种…

📰

查aigc免费网站靠谱吗?准确率98.54%的AI率报告带编号可核验,查重报告没有

AI 的发展太快了。很多同学在日常的作业和写作当中都会使用 AI,除知网、维普、万方这几个大家熟知的 论文查重 系统外, 很多学校也开始接入了 AIGC 检测系统。用得比较多的是大家熟知的知网 AIGC 检测、维普 AIGC 检测,但也有很多垂直型的 A…

📰

aigc检测器哪个学校在用?中南大学、湘潭大学等高校AI率查重系统清单

AI 的发展太快了。很多同学在日常的作业和写作当中都会使用 AI,除知网、维普、万方这几个大家熟知的 论文查重 系统外, 很多学校也开始接入了 AIGC 检测系统。用得比较多的是大家熟知的知网 AIGC 检测、维普 AIGC 检测,但也有很多垂直型的 A…

📰

Oracle 11g透明网关访问SQL Server:从安装配置到排错完整指南

做Oracle开发和运维的朋友,早晚会碰到这么个需求:Oracle库要读SQL Server的数据。以前我都是写ETL脚本定时抽取,或者让开发同事导出CSV再灌进Oracle,费劲不说,实时性还差。后来在项目里用上了Oracle11g透明网关&#x…

📰

STM32CubeMX生成IAR工程实战指南:配置、编译与常见坑

今天聊聊嵌入式开发里一个挺常见的需求:用STM32CubeMX生成IAR工程。网上有个词叫“STM32CubeMX2”,其实就是我们平时说的STM32CubeMX,可能版本号写顺了多打了个2。最近在一个老项目里接手了一批IAR工程,代码维护全靠CubeMX重新生成…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬