尧图网络 高端网站定制 · 原创设计
免费咨询热线
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/11/7 21:02:07
智慧园区照明监控与能源管理系统方案

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

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

📅 2026/11/14 16:08:39
靠谱工厂的AI热成像检测机,如何选对才省心?

靠谱工厂的AI热成像检测机,如何选对才省心?

在工业自动化与智能制造成熟度不断提升的当下,热成像检测机已从传统红外测温设备,进化为一套融合AI视觉、大数据分析与边缘计算的复合型智能装备。工厂产线对温度敏感点的实时监测、设备诊断及质量管控需求日益精细,如何在众多品牌与型号中选…

📅 2026/11/14 1:59:27
MORE NEWS

更多资讯

📰

电工证找工作有前途吗 在哪考实操考试心里没底怕挂科

电工证找工作有前途吗 在哪考实操考试心里没底怕挂科 实操考试心里没底怕挂科,这是大多数准备考电工证的人心里的真实想法。尤其是像你这种信阳浉河区公路工程的从业者,对电工证的需求不光是上岗的“门槛”,更是职业发展的“敲门砖”。那么,…

📰

河北考电工证被曝光千万别踩坑,外省证怎么转?看这篇就够了

河北考电工证被曝光千万别踩坑,外省证怎么转?看这篇就够了 之前考的证在外省能不能转过来?这是很多人在考电工证前最担心的问题,特别是那些已经在外地工作、但想回到河北发展的朋友。最近“ 河北考电工证被曝光…

📰

南方电力网电工证怎么考?考前押题能帮你省下30%时间

南方电力网电工证怎么考?考前押题能帮你省下30%时间 刚毕业的你正为找工作发愁,手里却没有一张能让你顺利入职的特种作业证,尤其是南方电力网电工证,成了很多电气类毕业生求职的“硬门槛”。别急,今天咱们就从零开始,手把手教你考南方电力网电工证,…

📰

特种工是化验员吗知乎保姆级教程:你急需的特种作业证真相

特种工是化验员吗知乎保姆级教程:你急需的特种作业证真相 你是不是正被“ 急需特种作业证才能上岗找工作 ”这句话压得喘不过气?别急,今天这篇【 特种工是化验员吗知乎保姆级教程…

📰

电工证是全国通用不?郑州报考避坑指南,证书过期了不知道怎么复审延期

电工证是全国通用不?郑州报考避坑指南,证书过期了不知道怎么复审延期 证书过期了不知道怎么复审延期,这是很多特种作业持证人的痛点。尤其是在郑州,不少电工从业者因为对证件复审流程不了解,导致证书失效,影响了工作和收入。本文就围绕“…

📰

电工证成绩怎么查在哪考才能顺利上岗找工作

电工证成绩怎么查在哪考才能顺利上岗找工作 你是不是也正为找工作发愁?手里没个电工证,连面试资格都没有,这是很多转岗从业者的切身感受。特别是像三门峡这样的地区,用人单位对特种作业证的要求越来越严格,电工证更是基础中的基础。但问题是,…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

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

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

📞 💬