Hey guy,
This is my .cursorrules file.
I hope it is useful for you.
{
"examples": {
"description": "使用示例,可直接复制使用",
"createBasicModule": {
"description": "创建基础CRUD模块",
"command": "cursor createFeatureModule --name Machine --description '机器管理' --fields 'name,description,status'",
"output": [
"创建 MachineEntity.java",
"创建 MachineRepository.java",
"创建 MachineDTO.java, MachineCreateDTO.java, MachineUpdateDTO.java",
"创建 MachineService.java, MachineServiceImpl.java",
"创建 MachineController.java",
"创建 MachineException.java, MachineExceptionHandler.java"
]
},
"createBusinessService": {
"description": "创建纯业务服务(不涉及数据库)",
"command": "cursor createBusinessService --name ImageGeneration --businessType ai/generation --description 'AI图片生成服务'",
"output": [
"创建 src/main/java/com/shnet/admin/service/ai/generation/ImageGenerationService.java"
]
},
"createScheduler": {
"description": "创建定时任务",
"examples": [
{
"name": "leader专属定时任务",
"command": "cursor createScheduler --name TaskClean --description '任务清理' --schedule '0 0 2 * * ?' --leaderOnly true"
},
{
"name": "所有节点执行的定时任务",
"command": "cursor createScheduler --name HealthCheck --description '健康检查' --schedule '0/30 * * * * ?' --leaderOnly false"
}
]
},
"createComplexProcessor": {
"description": "创建复杂业务处理器",
"steps": [
"1. 需求分析和伪代码设计:",
"cursor complexBusinessProcess --phase analysis --name OrderProcess --description '订单处理流程:\n1. 接收订单请求\n2. 校验订单数据\n3. 检查库存\n4. 计算价格\n5. 生成订单\n6. 通知相关系统'",
"",
"2. 创建处理器相关类:",
"cursor createComplexProcessor --name ImageGeneration --types \"Text2Image,Image2Image\""
],
"output": [
"创建 ImageGenerationProcessor.java (接口)",
"创建 ImageGenerationContext.java (上下文)",
"创建 AbstractImageGenerationProcessor.java (抽象类)",
"创建 Text2ImageProcessor.java, Image2ImageProcessor.java (具体实现)",
"创建 ImageGenerationProcessorFactory.java (工厂类)"
]
},
"logUsage": {
"description": "日志记录示例",
"code": [
"// 记录操作日志",
"Map<String, Object> logData = new HashMap<>();",
"logData.put(\"newConfig\", savedConfig);",
"",
"logService.createLog(new LogCreateDto(",
" new LogDataDto(\"addMachineConfig\", logData),",
" \"info\",",
" \"Added new machine configuration\",",
" \"TaskService\",",
" getCurrentUserId()",
"));"
]
},
"controllerUsage": {
"description": "Controller 层使用示例",
"code": [
"@Tag(name = \"机器管理\", description = \"机器管理相关接口\")",
"@RestController",
"@RequestMapping(\"/admin/machines\")",
"@Validated",
"@Slf4j",
"public class MachineController extends BaseController {",
"",
" @Operation(summary = \"创建机器\", description = \"创建新的机器配置\")",
" @PostMapping(\"/create\")",
" @PreAuthorize(\"hasPermission(null, null, 'operate_machines')\")",
" public ResponseEntity<ApiResult> createMachine(@RequestBody @Valid MachineCreateDTO createDTO) {",
" String userId = getCurrentUserId();",
" MachineDTO result = machineService.createMachine(userId, createDTO);",
" return renderOk(mapOf(\"machine\", result));",
" }",
"}"
]
}
},
"projectType": {
"language": "java",
"framework": "spring-boot",
"description": "这是一个基于Spring Boot的Java后台管理系统",
"orm": "spring-data-mongodb",
"database": "mongodb",
"features": [
"RESTful API",
"Swagger文档",
"Spring Data MongoDB",
"统一响应格式",
"统一异常处理"
]
},
"projectRules": {
"description": "Java Spring Boot 后台管理系统项目规范",
"codeStyle": {
"language": "java",
"framework": "spring-boot",
"indentation": 4,
"lineLength": 120
},
"architecture": {
"packageStructure": {
"controller": {
"description": "处理HTTP请求,返回ResponseEntity<ApiResult>",
"baseClass": "BaseController",
"imports": {
"required": [
"com.shnet.admin.controller.base.BaseController",
"com.shnet.admin.core.api.ApiResult"
]
},
"dataStructure": {
"request": "只能使用 *DTO 作为请求参数",
"response": "只能使用 *DTO 作为响应数据,禁止直接返回 Entity"
},
"annotations": {
"class": [
"@Tag(name = \"${description}\", description = \"${description}相关接口\")",
"@ApiResponse(responseCode = \"200\", description = \"请求已处理,具体结果参考ApiResult的code和message\")",
"@RestController",
"@RequestMapping(\"/admin/${path}\")",
"@Validated",
"@Slf4j"
],
"method": [
"@Operation(summary = \"${summary}\", description = \"${description}\")",
"@PreAuthorize(\"hasPermission(null, null, '${permission}')\")",
"@ApiResponse(responseCode = \"200\", description = \"请求已处理,具体结果参考ApiResult的code和message\")"
]
},
"responseHandling": {
"description": "统一使用HTTP 200状态码,具体错误信息通过ApiResult传递",
"format": {
"success": {
"httpStatus": 200,
"apiResult": {
"code": "OK",
"message": null
}
},
"error": {
"httpStatus": 200,
"apiResult": {
"code": "对应的错误码",
"message": "具体的错误信息"
}
}
}
}
},
"service": {
"description": "业务逻辑层,实现具体业务功能",
"types": {
"database": {
"description": "涉及数据库操作的服务",
"structure": {
"interface": "src/main/java/com/shnet/admin/service/*Service.java",
"implementation": "src/main/java/com/shnet/admin/service/impl/*ServiceImpl.java"
},
"pattern": "接口+实现类模式",
"userContext": {
"description": "用户上下文传递",
"parameter": "String userId",
"usage": "用于记录操作日志"
}
},
"business": {
"description": "纯业务逻辑服务(不涉及数据库)",
"structure": "src/main/java/com/shnet/admin/service/${businessType}/*Service.java",
"pattern": "只需实现类",
"example": "leaderElection/LeaderElectionService.java"
}
}
},
"mongodb": "MongoDB数据访问层接口,存放所有Repository接口",
"mongodb.entity": "MongoDB实体类定义,存放所有Entity类",
"dto": "数据传输对象,用于接口请求和响应",
"config": "配置类",
"utils": "工具类",
"core": {
"description": "核心功能包,包含基础组件和通用功能",
"subPackages": {
"api": "API响应相关类,如ApiResult、ApiCode等",
"page": {
"description": "统一分页封装",
"classes": {
"Page": "分页数据封装类,所有列表接口必须使用此类"
},
"usage": {
"description": "分页查询规范",
"methods": {
"mongoTemplate": {
"description": "使用MongoTemplate进行复杂查询和分页",
"example": [
"// 1. 构建查询条件",
"Query query = new Query();",
"if (StringUtils.isNotBlank(param)) {",
" query.addCriteria(Criteria.where(\"field\").regex(param));",
"}",
"",
"// 2. 获取总数",
"long total = mongoTemplate.count(query, EntityClass.class);",
"",
"// 3. 添加分页条件",
"query.skip((page - 1) * size).limit(size);",
"",
"// 4. 执行查询",
"List<EntityClass> list = mongoTemplate.find(query, EntityClass.class);",
"",
"// 5. 使用Page封装结果",
"return new Page<>(list, total, page, size);"
]
}
}
}
},
"exception": {
"description": "异常处理相关类",
"components": {
"AbstractBusinessException": "所有业务异常的基类",
"ExceptionHandler": "异常处理器接口",
"*Exception": "具体业务异常类",
"*ExceptionHandler": "具体业务异常处理器"
}
},
"distributionLock": "分布式锁实现",
"security": "安全相关功能",
"utils": "核心工具类"
}
},
"processor": {
"description": "复杂业务处理流包",
"structure": {
"base": "src/main/java/com/shnet/admin/processor/base",
"impl": "src/main/java/com/shnet/admin/processor/impl"
},
"patterns": {
"strategy": "不同实现策略的选择",
"template": "定义算法骨架,让子类实现具体步骤",
"chain": "责任链模式处理复杂流程",
"factory": "创建具体策略实例"
}
},
"schedule": {
"description": "定时任务包,存放所有定时任务类",
"baseClass": "BaseScheduler",
"structure": {
"path": "src/main/java/com/shnet/admin/schedule",
"naming": "*Scheduler"
},
"executionMode": {
"leaderOnly": {
"description": "只允许leader节点执行的定时任务",
"implementation": [
"@Override",
"protected boolean isLeaderOnly() {",
" return true;",
"}"
]
},
"allNodes": {
"description": "所有节点都可以执行的定时任务",
"implementation": [
"@Override",
"protected boolean isLeaderOnly() {",
" return false;",
"}"
]
}
},
"annotations": {
"required": [
"@Component",
"@EnableScheduling"
],
"scheduling": "@Scheduled"
}
}
},
"paths": {
"repository": "src/main/java/com/shnet/admin/mongodb",
"entity": "src/main/java/com/shnet/admin/mongodb/entity",
"core": "src/main/java/com/shnet/admin/core"
}
},
"conventions": {
"naming": {
"controller": "*Controller",
"service": {
"interface": "*Service",
"implementation": "*ServiceImpl"
},
"repository": "*Repository",
"entity": "*Entity",
"dto": "*DTO"
},
"annotations": {
"controller": [
"@RestController",
"@RequestMapping",
"@Tag",
"@Validated",
"@Slf4j"
],
"service": [
"@Service",
"@Autowired"
],
"repository": [],
"entity": [
"@Document",
"@Data",
"@Id",
"@Version"
]
},
"service": {
"database": {
"interface": {
"location": "src/main/java/com/shnet/admin/service",
"naming": "*Service"
},
"implementation": {
"location": "src/main/java/com/shnet/admin/service/impl",
"naming": "*ServiceImpl"
}
},
"business": {
"location": "src/main/java/com/shnet/admin/service/${businessType}",
"naming": "*Service"
}
}
},
"documentation": {
"swagger": {
"controller": {
"required": ["@Tag", "@Operation", "@Parameter"],
"responseFormat": "ResponseEntity<ApiResult>"
}
},
"methods": {
"format": "/**\n * @param [参数名] [参数描述]\n * @return [返回值描述]\n */"
}
},
"security": {
"authentication": "@PreAuthorize",
"validation": ["@Valid", "@Validated"]
},
"errorHandling": {
"exceptions": {
"custom": "BusinessException",
"validation": "MethodArgumentNotValidException"
},
"response": "ApiResult",
"baseException": {
"class": "AbstractBusinessException",
"requiredFields": {
"ERROR_CODE_PREFIX": "String (业务异常前缀)",
"HTTP_STATUS": "HttpStatus (默认HttpStatus.OK)"
}
},
"exceptionHandler": {
"interface": "ExceptionHandler",
"implementation": {
"annotations": ["@Component"],
"template": [
"@Component",
"public class ${name}ExceptionHandler implements ExceptionHandler<${name}Exception> {",
" // ExceptionHandler接口提供默认实现",
"}"
]
}
}
},
"sourceRoot": {
"description": "源代码根目录位置",
"rule": "源代码目录(src/)应与.cursorrules文件位于同一目录下",
"example": {
"cursorrules": "ai-admin/.cursorrules",
"sourceCode": "ai-admin/src/..."
}
}
},
"prompts": {
"createController": "创建一个RESTful控制器,包含标准的CRUD操作和适当的权限控制",
"createService": "创建一个服务接口及其实现类,包含业务逻辑和事务管理",
"createDTO": "创建一个DTO类,包含必要的验证注解和序列化配置",
"createEntity": "创建一个实体类,包含JPA注解和审计字段"
},
"bestPractices": {
"controller": [
"使用统一的响应格式 ResponseEntity<ApiResult>",
"添加适当的OpenAPI文档注解",
"实现参数验证",
"权限控制"
],
"service": [
"业务逻辑封装",
"事务管理",
"异常处理",
"日志记录"
],
"general": [
"使用统一的异常处理",
"遵循阿里巴巴Java开发规范",
"添加适当的注释和文档"
]
},
"taskChains": {
"createFeatureModule": {
"description": "创建完整的功能模块,包含Controller、Service、DTO、Entity等",
"steps": [
{
"name": "createEntity"
},
{
"name": "createRepository"
},
{
"name": "createDTO",
"variants": [
{
"suffix": "CreateDTO",
"purpose": "创建请求对象",
"validation": true
},
{
"suffix": "UpdateDTO",
"purpose": "更新请求对象",
"validation": true
},
{
"suffix": "DTO",
"purpose": "响应对象"
}
]
},
{
"name": "createService"
},
{
"name": "createController" },
{
"name": "createException"
},
{
"name": "createComplexProcessor",
"description": "创建复杂业务处理器",
"steps": [
{
"name": "createProcessorInterface"
},
{
"name": "createProcessorContext"
},
{
"name": "createAbstractProcessor"
},
{
"name": "createStrategyFactory"
}
]
},
{
"name": "createScheduler",
"description": "创建定时任务类",
"parameters": {
"name": "定时任务名称",
"description": "定时任务描述",
"schedule": "定时任务表达式",
"leaderOnly": "是否只允许leader执行"
},
"template": {
"path": "src/main/java/com/shnet/admin/schedule/${name}Scheduler.java",
"baseClass": "BaseScheduler",
"imports": [
"org.springframework.scheduling.annotation.EnableScheduling",
"org.springframework.scheduling.annotation.Scheduled",
"org.springframework.stereotype.Component",
"lombok.extern.slf4j.Slf4j"
],
"annotations": [
"@Slf4j",
"@Component",
"@EnableScheduling"
],
"methods": {
"isLeaderOnly": {
"description": "是否只允许leader执行",
"template": [
"@Override",
"protected boolean isLeaderOnly() {",
" return ${leaderOnly};",
"}"
]
},
"execute": {
"description": "定时任务执行入口",
"template": [
"@Scheduled(${schedule})",
"public void execute() {",
" if (!canExecuteSchedule()) {",
" return;",
" }",
" try {",
" doExecute();",
" } catch (Exception e) {",
" log.error(\"${description}执行异常\", e);",
" }",
"}"
]
},
"doExecute": {
"description": "具体任务实现",
"template": [
"private void doExecute() {",
" // 实现具体的任务逻辑",
"}"
]
}
}
}
}
],
"usage": {
"command": "createFeatureModule",
"parameters": {
"name": "模块名称(英文)",
"description": "模块描述(中文)",
"fields": "字段定义列表",
"security": "权限配置"
},
"example": {
"name": "Product",
"description": "产品管理",
"fields": [
{
"name": "name",
"type": "String",
"validation": "@NotBlank(message = \"名称不能为空\")",
"description": "产品名称"
}
],
"security": "operate_products"
}
}
},
"createBusinessService": {
"description": "创建纯业务逻辑服务类",
"parameters": {
"name": "服务名称",
"businessType": "业务类型(用作包名)",
"description": "服务描述"
},
"template": {
"path": "src/main/java/com/shnet/admin/service/${businessType}/${name}Service.java",
"annotations": ["@Service"],
"imports": []
}
},
"complexBusinessProcess": {
"steps": [
{
"phase": "需求分析",
"actions": [
"明确业务目标和范围",
"识别关键流程和决策点",
"定义输入输出",
"确定性能和扩展性要求"
]
},
{
"phase": "伪代码设计",
"template": [
"1. 流程概述",
"2. 核心步骤拆解",
"3. 关键决策点",
"4. 异常处理",
"5. 扩展点预留"
]
},
{
"phase": "方案讨论",
"focus": [
"流程合理性",
"扩展性考虑",
"性能影响",
"维护成本"
]
},
{
"phase": "代码实现",
"patterns": {
"strategy": {
"usage": "多种实现方式选择",
"structure": {
"interface": "${name}Strategy",
"implementations": "${name}${Type}Strategy"
}
},
"template": {
"usage": "固定流程不同实现",
"structure": {
"abstract": "Abstract${name}Processor",
"concrete": "${name}${Type}Processor"
}
}
}
}
]
}
},
"logging": {
"service": {
"interface": "LogService",
"methods": {
"createLog": {
"parameters": ["LogCreateDto logCreateDto"],
"usage": "记录用户操作日志",
"example": {
"description": "参考 MachineConfigServiceImpl.addMachineConfig 方法",
"code": [
"// 构建日志数据",
"Map<String, Object> logData = new HashMap<>();",
"logData.put(\"newConfig\", savedConfig);",
"",
"// 创建日志",
"logService.createLog(new LogCreateDto(",
" new LogDataDto(\"addMachineConfig\", logData), // 操作类型和数据",
" \"info\", // 日志级别",
" \"Added new machine configuration\", // 日志描述",
" \"TaskService\", // 服务名称",
" userID // 用户ID",
"));"
]
}
}
},
"dto": {
"LogCreateDto": {
"fields": [
"LogDataDto logData",
"String level",
"String message",
"String service",
"String userId"
]
},
"LogDataDto": {
"fields": [
"String operation",
"Map<String, Object> data"
]
}
}
}
}
}
As project become bigger and bigger, I realized Composer generate code can’t fit my thought. Though the bulk generate code is great, but it always have some error, so I have to check the generate code every time. This is not good experience.
I design this .cursorrules for solving these some.
For example,
one of my requirement is generate template code. So I design the ‘createBasicModule’ command. When I run this command, it will generate java CURD codes that fit my thought.
For the complex processor, I design the ‘createComplexProcessor’ command. If I do this step by step, first it will generate pseudocode, and then create target classes, finally generate true business code.
The code what generate by this rules is great. AI can follow the project structure and the code also fit the structure. After do this, I decrease check code times, it’s great experience for me.
All of the rules, you don’t have to design manually, you can generate them by AI. When your project structure changed, you need change the rules.