Rule Template
Rule Constraints
- Each rule file is limited to a maximum of 10,000 characters; content exceeding this limit will be automatically truncated.
- 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
| Layer | Responsibility | Constraints |
|---|---|---|
| Controller | Handle HTTP requests/responses, define APIs | - Must not directly operate on the database - Must call through the Service layer |
| Service | Implement business logic, manage transactions, validate data | - Must access the database via Mapper |
| Dao | Perform data persistence operations, define database query logic | - Must extend BaseMapper |
| DO | Map 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.xmlIV. 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
- Input Validation:
- Use
@Validannotations with JSR-303 validation constraints (e.g.,@NotBlank,@Size) - Never concatenate SQL strings directly to prevent injection attacks
- Use
- Transaction Management:
- Apply
@Transactionalonly on Service-layer methods - Avoid frequent transaction commits inside loops
- Apply
- Performance Optimization:
- Avoid executing database queries inside loops (prefer batch operations)
VIII. Code Style Guidelines
- Naming Conventions:
- Class names:
UpperCamelCase(e.g.,UserServiceImpl) - Method/variable names:
lowerCamelCase(e.g.,saveUser) - Constants:
UPPER_SNAKE_CASE(e.g.,MAX_LOGIN_ATTEMPTS)
- Class names:
- 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
- Code Formatting:
- Use IntelliJ IDEA's default Spring Boot code style
- Never manually adjust indentation (rely on IDEA auto-formatting)
IX. Deployment Guidelines
- Deployment Practices:
- Disable default
@EnableAutoConfigurationin production environments - Externalize sensitive information via
application.properties - Use
Spring Profilesto manage environment differences (e.g.,dev,prod)
- Disable default
X. Extensibility Design Guidelines
- Interface-First Design:
- Separate service interfaces (
UserService) from implementations (UserServiceImpl)
- Separate service interfaces (
- Extension Points:
- Provide
StrategyorTemplatepatterns for key business logic to support future extensions
- Provide
- Logging Standards:
- Use
SLF4Jfor logging (never useSystem.out.printlndirectly) - Log core operations at
INFOlevel and exceptions atERRORlevel
- Use
