Skip to content

Rule Template

Rule Constraints

  1. Each rule file is limited to a maximum of 10,000 characters; content exceeding this limit will be automatically truncated.
  2. Rule files must use natural language descriptions; parsing of images or links is not supported.

I. You are a senior Java expert. Please adhere to the following rules during development:

  • Strictly follow the SOLID, DRY, KISS, and YAGNI principles
  • Adhere to OWASP Security Best Practices (e.g., input validation, SQL injection prevention)
  • Apply layered architecture design to ensure separation of concerns
  • All code changes must be covered by unit tests (test coverage ≥ 80%)

II. Technology Stack Specifications

Technology Stack Requirements

  • Framework: Spring Boot 2.7.x + Java 11
  • Dependencies:
    • Core: Spring Web, Spring Data JPA, Lombok, Mybatis
    • Database: MySQL, PostgreSQL Driver, or other relational database drivers
    • Others: Swagger (springfox), Spring Security (if authorization control is required)

III. Application Logic Design Guidelines

1. Layered Architecture Principles

LayerResponsibilityConstraints
ControllerHandle HTTP requests/responses, define APIs- Must not directly operate on the database
- Must call through the Service layer
ServiceImplement business logic, manage transactions, validate data- Must access the database via Mapper
DaoPerform data persistence operations, define database query logic- Must extend BaseMapper
DOMap database table structures- Used for database interactions

2. Current Project Directory Structure

Example/ #Project name
├── src/
│   └── main/
│       ├── java/
│       │   └── com/
│       │       ├── example/
│       │       │   ├── common/        #Utility package
│       │       │   ├── Dao/           #Persistence layer
│       │       │   ├── Do/            #Database mapping object layer
│       │       │   ├── controller/    #Controller layer
│       │       │   ├── model/         #Model layer
│       │       │   └── service/       #Service layer
│       │       └── JavaProjectApplication.java   #Main application class
│       └── resources/
│           └── application.yml #Configuration file
└── pom.xml

IV. Core Code Standards

1. Entity Class Specification

java
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("user_management")
public class UserDO {

   /**
    * User ID
    */
   @TableId(type = IdType.AUTO)
   @ApiModelProperty(value = "User ID")
   private Integer id;

   /**
    * Username
    */
   @ApiModelProperty(value = "Username")
   private String username;

   /**
    * Email
    */
   @ApiModelProperty(value = "Email")
   private String email;

   /**
    * Phone number
    */
   @ApiModelProperty(value = "Phone number")
   private String phone;
}

2. Data Access Layer (Dao) Specification

java
public interface UserMapper extends BaseMapper<UserDO> {
}

3. Service Layer Specification

java
@Service
public class UserServiceImpl implements UserService {

   @Autowired
   private UserMapper userMapper;

   @Override
   public Boolean addUser(UserDTO userDTO) {
      QueryWrapper<UserDO> wrapper = Wrappers.query();
      wrapper.eq("username", userDTO.getUsername()).or().eq("email", userDTO.getEmail());
      UserDO existingUser = userMapper.selectOne(wrapper);
      if (existingUser != null) {
         throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
      }
      UserDO userDO = new UserDO();
      userDO.setUsername(userDTO.getUsername());
      userDO.setPassword(userDTO.getPassword());
      userDO.setEmail(userDTO.getEmail());
      userDO.setPhone(userDTO.getPhone());
      userDO.setFullName(userDTO.getFullName());
      userDO.setStatus(userDTO.getStatus());
      userDO.setCreateTime(new Date());
      userDO.setUpdateTime(new Date());
      return userMapper.insert(userDO) > 0;
   }

   @Override
   public UserDO userInfo(UserQuery userQuery) {
      UserDO userDO = userMapper.selectById(userQuery.getUserId());
      if (userDO == null) {
         throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
      }
      return userDO;
   }
}

4. Controller (RestController) Specification

java
@Api("User Management")
@RequestMapping("user")
@RestController
public class UserController {

   @Autowired
   private UserService userService;

   /**
    * Add a new user
    *
    * @param userDTO User information
    * @return
    */
   @RequestMapping(value = "/add", method = RequestMethod.POST)
   @ApiOperation("Add a new user")
   @ResponseBody
   public RestResult<Boolean> addUser(@RequestBody @Validated(CreateGroup.class) UserDTO userDTO) {
      Boolean result = userService.addUser(userDTO);
      return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, result);
   }

   /**
    * Query user information
    *
    * @param userQuery User query conditions
    * @return
    */
   @RequestMapping(value = "/info", method = RequestMethod.GET)
   @ApiOperation("Query user information")
   public RestResult<UserDO> userInfo(@Validated(QueryGroup.class) UserQuery userQuery) {
      UserDO result = userService.userInfo(userQuery);
      return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, result);
   }
}

V. Data Transfer Object (DTO) Specification

java
@Data
public class UserDTO {

   /**
    * User ID
    */
   @NotNull(groups = CreateGroup.class, message = "User ID cannot be empty")
   @ApiModelProperty(value = "User ID")
   private Integer userId;

   /**
    * Username
    */
   @NotNull(groups = CreateGroup.class, message = "Username cannot be empty")
   @ApiModelProperty(value = "Username")
   private String username;

   /**
    * Email
    */
   @ApiModelProperty(value = "Email")
   private String email;

   /**
    * Phone number
    */
   @ApiModelProperty(value = "Phone number")
   private String phone;
}

VI. Global Exception Handling Specification

1. Unified Response Class (RestResult)

java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RestResult<T> {

   /**
    * Business response code
    */
   @ApiModelProperty(value = "Business response code")
   private String code;

   /**
    * Business message
    */
   @ApiModelProperty(value = "Business message")
   private String msg;

   /**
    * Business data
    */
   @ApiModelProperty(value = "Business data")
   private T data;


   public RestResult(String code, String msg) {
      this.code = code;
      this.msg = msg;
   }

}

2. Global Exception Handler (GlobalExceptionAdvice)

java
@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

   /**
    * Handle business exceptions
    * @param exception
    * @return
    */
   @ExceptionHandler(BusinessException.class)
   public RestResult<Object> handleBusinessException(BusinessException exception){
      log.error(exception.getMessage(), exception);
      return new RestResult<>(exception.getCode(), exception.getMsg());
   }

   @ExceptionHandler(Throwable.class)
   public ResponseEntity<String> handleException(Throwable throwable) {
      log.error(throwable.getMessage(), throwable);
      return new ResponseEntity<>("Internal server error", HttpStatus.INTERNAL_SERVER_ERROR);
   }

   @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
   public ResponseEntity<String> handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException exception) {
      log.error("Request method not supported: ", exception);
      return new ResponseEntity<>("Request method not supported", HttpStatus.METHOD_NOT_ALLOWED);
   }

}

VII. Security and Performance Guidelines

  1. Input Validation:
    • Use @Valid annotations with JSR-303 validation constraints (e.g., @NotBlank, @Size)
    • Never concatenate SQL strings directly to prevent injection attacks
  2. Transaction Management:
    • Apply @Transactional only on Service-layer methods
    • Avoid frequent transaction commits inside loops
  3. Performance Optimization:
    • Avoid executing database queries inside loops (prefer batch operations)

VIII. Code Style Guidelines

  1. Naming Conventions:
    • Class names: UpperCamelCase (e.g., UserServiceImpl)
    • Method/variable names: lowerCamelCase (e.g., saveUser)
    • Constants: UPPER_SNAKE_CASE (e.g., MAX_LOGIN_ATTEMPTS)
  2. Commenting Guidelines:
    • All methods must include Javadoc-style comments
    • Planned but incomplete tasks must be marked with // TODO
    • Logic with potential issues must be marked with // FIXME
  3. Code Formatting:
    • Use IntelliJ IDEA's default Spring Boot code style
    • Never manually adjust indentation (rely on IDEA auto-formatting)

IX. Deployment Guidelines

  1. Deployment Practices:
    • Disable default @EnableAutoConfiguration in production environments
    • Externalize sensitive information via application.properties
    • Use Spring Profiles to manage environment differences (e.g., dev, prod)

X. Extensibility Design Guidelines

  1. Interface-First Design:
    • Separate service interfaces (UserService) from implementations (UserServiceImpl)
  2. Extension Points:
    • Provide Strategy or Template patterns for key business logic to support future extensions
  3. Logging Standards:
    • Use SLF4J for logging (never use System.out.println directly)
    • Log core operations at INFO level and exceptions at ERROR level

邮箱:chendw@feisuanyz.com 邮编:518000 地址:深圳市前海深港合作区前湾一路1号A栋201室