Java 开发规范
参考来源: Google Java Style Guide、阿里巴巴 Java 开发手册
工具链
# Maven
mvn clean compile # 编译
mvn test # 运行测试
mvn verify # 运行所有检查
# Gradle
./gradlew build # 构建
./gradlew test # 运行测试
命名约定
类成员顺序
public class Example {
// 1. 静态常量
public static final String CONSTANT = "value";
// 2. 静态变量
private static Logger logger = LoggerFactory.getLogger(Example.class);
// 3. 实例变量
private Long id;
// 4. 构造函数
public Example() { }
// 5. 静态方法
public static Example create() { return new Example(); }
// 6. 实例方法(公共 → 私有)
public void doSomething() { }
private void helperMethod() { }
// 7. getter/setter(或使用 Lombok)
}
DTO/VO 类规范
// ❌ 手写 getter/setter
public class UserDTO {
private Long id;
private String name;
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
// ... 大量样板代码
}
// ✅ 使用 Lombok
@Data
public class UserDTO {
private Long id;
private String name;
}
批量查询规范
// ❌ 1700 个 ID 一次查询
List<User> users = userRepository.findByIdIn(allIds); // IN 子句过长
// ✅ 分批查询工具方法
public static <T, R> List<R> batchQuery(List<T> params, int batchSize,
Function<List<T>, List<R>> queryFn) {
List<R> result = new ArrayList<>();
for (int i = 0; i < params.size(); i += batchSize) {
List<T> batch = params.subList(i, Math.min(i + batchSize, params.size()));
result.addAll(queryFn.apply(batch));
}
return result;
}
// 使用
List<User> users = batchQuery(allIds, 500, ids -> userRepository.findByIdIn(ids));
N+1 查询防范
// ❌ N+1:循环内逐行查询 count
records.forEach(record -> {
long count = deviceRepo.countByDeviceId(record.getDeviceId()); // 每条触发一次查询
record.setDeviceCount(count);
});
// ✅ 循环外批量查询 + Map 查找
List<String> deviceIds = records.stream()
.map(Record::getDeviceId).distinct().collect(Collectors.toList());
Map<String, Long> countMap = deviceRepo.countByDeviceIdIn(deviceIds).stream()
.collect(Collectors.toMap(CountDTO::getDeviceId, CountDTO::getCount));
records.forEach(r -> r.setDeviceCount(countMap.getOrDefault(r.getDeviceId(), 0L)));
常见 N+1 场景及修复模式:
并发安全规范
// ❌ read-modify-write 竞态条件
PointsAccount account = accountRepo.findById(id);
account.setBalance(account.getBalance() + points); // 并发时丢失更新
accountRepo.save(account);
// ✅ 方案一:原子更新 SQL
@Modifying
@Query("UPDATE PointsAccount SET balance = balance + :points WHERE id = :id")
int addBalance(@Param("id") Long id, @Param("points") int points);
// ✅ 方案二:乐观锁
@Version
private Long version; // Entity 中添加版本字段
// ❌ check-then-act 无兜底(并发下可能重复结算)
if (!rewardRepo.existsByTenantIdAndPeriod(tenantId, period)) {
rewardRepo.save(new RankingReward(...));
}
// ✅ 唯一索引兜底 + 异常捕获
// DDL: UNIQUE INDEX uk_tenant_period (tenant_id, ranking_type, period, rank_position)
try {
rewardRepo.save(new RankingReward(...));
} catch (DataIntegrityViolationException e) {
log.warn("重复结算已被唯一索引拦截: tenantId={}, period={}", tenantId, period);
}
异常处理
// ✅ 好:捕获具体异常,添加上下文
try {
user = userRepository.findById(id);
} catch (DataAccessException e) {
throw new ServiceException("Failed to find user: " + id, e);
}
// ✅ 好:资源自动关闭
try (InputStream is = new FileInputStream(file)) {
// 使用资源
}
// ❌ 差:捕获过宽
catch (Exception e) { e.printStackTrace(); }
空值处理
// ✅ 使用 Optional
public Optional<User> findById(Long id) {
return userRepository.findById(id);
}
// ✅ 参数校验
public void updateUser(User user) {
Objects.requireNonNull(user, "user must not be null");
}
// ✅ 安全的空值处理
String name = Optional.ofNullable(user)
.map(User::getName)
.orElse("Unknown");
并发编程
// ✅ 使用 ExecutorService
ExecutorService executor = Executors.newFixedThreadPool(10);
Future<Result> future = executor.submit(() -> doWork());
// ✅ 使用 CompletableFuture
CompletableFuture<User> future = CompletableFuture
.supplyAsync(() -> findUser(id))
.thenApply(user -> enrichUser(user));
// ❌ 差:直接创建线程
new Thread(() -> doWork()).start();
测试规范 (JUnit 5)
class UserServiceTest {
@Test
@DisplayName("根据 ID 查找用户 - 用户存在时返回用户")
void findById_whenUserExists_returnsUser() {
// given
when(userRepository.findById(1L)).thenReturn(Optional.of(expected));
// when
Optional<User> result = userService.findById(1L);
// then
assertThat(result).isPresent();
assertThat(result.get().getName()).isEqualTo("test");
}
}
Spring Boot 规范
// ✅ 构造函数注入
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository userRepository;
}
详细规则、修复模板和检查清单见 references/spring.md
输入校验规范
常见 DTO 字段校验速查:
// ❌ 无校验,任意输入直接进入业务逻辑
@PostMapping("/ship")
public Result ship(@RequestBody ShippingRequest request) { ... }
// ✅ 完整校验
@PostMapping("/ship")
public Result ship(@RequestBody @Valid ShippingRequest request) { ... }
public record ShippingRequest(
@NotNull Long orderId,
@NotBlank @Size(max = 500) String shippingInfo,
@Pattern(regexp = "pending|shipped|delivered") String giftStatus
) {}
// ❌ quantity 只有 @NotNull,负数会导致 Redis DECRBY 反向加库存
public record CreateOrderRequest(