Spring Boot 服务的 Java 编码规范:命名、不可变性(Immutability)、Optional 使用、流(Streams)、异常处理、泛型(Generics)和项目布局。
适用于 Spring Boot 服务中易读、可维护的 Java (17+) 代码规范。
// ✅ 类(Classes)/ 记录(Records):大驼峰式(PascalCase)
public class MarketService {}
public record Money(BigDecimal amount, Currency currency) {}
// ✅ 方法/字段:小驼峰式(camelCase)
private final MarketRepository marketRepository;
public Market findBySlug(String slug) {}
// ✅ 常量:大写下划线命名式(UPPER_SNAKE_CASE)
private static final int MAX_PAGE_SIZE = 100;
// ✅ 优先使用记录(Records)和 final 字段
public record MarketDto(Long id, String name, MarketStatus status) {}
public class Market {
private final Long id;
private final String name;
// 仅提供 getter,不提供 setter
}
// ✅ find* 方法返回 Optional
Optional<Market> market = marketRepository.findBySlug(slug);
// ✅ 使用 map/flatMap 而不是 get()
return market
.map(MarketResponse::from)
.orElseThrow(() -> new EntityNotFoundException("Market not found"));
// ✅ 使用流进行转换,保持流水线简短
List<String> names = markets.stream()
.map(Market::name)
.filter(Objects::nonNull)
.toList();
// ❌ 避免复杂的嵌套流;为了清晰起见,优先使用循环
MarketNotFoundException)catch (Exception ex),除非是进行集中式重抛(Rethrow)或日志记录throw new MarketNotFoundException(slug);
public <T extends Identifiable> Map<Long, T> indexById(Collection<T> items) { ... }
src/main/java/com/example/app/
config/
controller/
service/
repository/
domain/
dto/
util/
src/main/resources/
application.yml
src/test/java/... (结构与 main 保持镜像)
private static final Logger log = LoggerFactory.getLogger(MarketService.class);
log.info("fetch_market slug={}", slug);
log.error("failed_fetch_market slug={}", slug, ex);
@Nullable;否则使用 @NonNull@NotNull, @NotBlank)记住:保持代码的意图清晰、类型安全且具有可观测性。除非证明有必要,否则应优先考虑可维护性而非微优化。
npx skills add codelably/java-coding-standards下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer