java-rules

Java 编码规范,包含代码风格、设计模式、安全性与测试实践,面向 .java、pom.xml、build.gradle 及常见生态(Spring、Spring Boot、JPA、Hibernate、JUnit、Maven、Gradle)。触发条件示例:.java、pom.xml、build.gradle、Spring、Spring Boot、JPA、Hibernate、JUnit、Maven、Gradle。

仓库最近推送
GitHub Stars
180
Forks
21
Issues / PRs
0

安装方式

先用 Prompt 核对来源与依赖。也可下载安装包。

用 AI 助手安装

复制提示词,让助手先核对固定版本和依赖。

查看 Prompt收起 Prompt
先检查当前 Agent 是否已安装 SkillPI Skill Finder。如果尚未安装,请按官方仓库的说明安装并启用:https://github.com/Findskills/skillpi。然后使用 Skill Finder 打开此 SkillPI 详情页并定位 "java-rules":https://skillpi.com/zh/skills/deepskill-533d627df5f338c90708dfa7d803c09d87af4312be95dc3ae258b31e3876fab9。安装前核对上游来源和版本:https://github.com/softspark/ai-toolkit。来源不一致时停止并说明差异。核对通过后,用 Skill Finder 安装目标 Skill,并报告安装路径和来源版本。

来源与配置

github.com

配置方式待核实

请查看原始来源中的适用工具、依赖和权限要求。

安装实测待补充

Java 编码规范,包含代码风格、设计模式、安全性与测试实践,面向 .java、pom.xml、build.gradle 及常见生态(Spring、Spring Boot、JPA、Hibernate、JUnit、Maven、Gradle)。触发条件示例:.java、pom.xml、build.gradle、Spring、Spring Boot、JPA、Hibernate、JUnit、Maven、Gradle。

0 下载

介绍来源: third_party · softspark · 0.0.1 参考来源

SkillPi 解读

能完成的任务
翻译待完成,请参阅来源文档。
输入和输出
翻译待完成,请参阅来源文档。
实测状态
未测试

文件浏览

在原站浏览文件 ↗

原始 SKILL.md

打开原文 ↗
Frontmatter
name: java-rules
description: "Java coding rules: style, patterns, security, testing. Triggers: .java, pom.xml, build.gradle, Spring, Spring Boot, JPA, Hibernate, JUnit, Maven, Gradle."
effort: medium
user-invocable: false
allowed-tools: Read

Java Rules

These rules come from app/rules/java/ in ai-toolkit. They cover the project's standards for coding style, frameworks, patterns, security, and testing in Java. Apply them when writing or reviewing Java code.

Java Coding Style

Naming

  • PascalCase: classes, interfaces, enums, records, annotations.
  • camelCase: methods, variables, parameters.
  • UPPER_SNAKE: constants (static final).
  • Package names: lowercase, dot-separated, reverse domain (com.company.project).
  • No Hungarian notation. No I prefix on interfaces.

Modern Java (17+)

  • Use record for immutable data carriers. No need for Lombok in most cases.
  • Use sealed classes/interfaces for restricted hierarchies.
  • Use pattern matching: if (obj instanceof String s) instead of cast.
  • Use switch expressions with arrow syntax and exhaustiveness.
  • Use text blocks (""") for multiline strings (SQL, JSON, HTML).

Types

  • Use var for local variables when the type is obvious from the right-hand side.
  • Use Optional<T> for return types that may be absent. Never for fields or params.
  • Prefer List.of(), Map.of(), Set.of() for immutable collections.
  • Use Stream for collection transformations. Avoid streams for simple iterations.

Classes

  • Prefer composition over inheritance. Use interfaces for abstraction.
  • Keep classes focused: single responsibility.
  • Use final on classes not designed for extension.
  • Use private constructors + static factory methods for controlled instantiation.
  • Records over POJOs for value types. Lombok only if records are insufficient.

Methods

  • Max 20-30 lines per method. Extract when longer.
  • Use @Override on every overridden method.
  • Return empty collections over null. Use Collections.emptyList() or List.of().
  • Avoid checked exceptions for programming errors. Use runtime exceptions.

Formatting

  • Use project formatter (Google Java Format or IDE-configured).
  • Use @SuppressWarnings sparingly and with specific warning names.
  • Use final for parameters and local variables where practical.

Nullability

  • Annotate with @Nullable / @NonNull from JSpecify or JetBrains.
  • Use Objects.requireNonNull() at public API boundaries.
  • Never return null from collections or arrays. Return empty.
  • Use Optional for genuinely optional return values.

Documentation

  • Javadoc on all public classes and methods.
  • Use @param, @return, @throws tags for public API methods.
  • Skip Javadoc for obvious getters, toString(), and equals().

Java Frameworks

Spring Boot

  • Use Spring Boot 3+ with Java 17+ minimum.
  • Use @RestController for REST APIs. Return ResponseEntity for status control.
  • Use @Valid + Jakarta Bean Validation for request validation.
  • Use profiles (@Profile) for environment-specific configuration.
  • Use application.yml over application.properties for readability.
  • Externalize config: env vars > config files > hardcoded defaults.

Spring Data JPA

  • Use repository interfaces extending JpaRepository.
  • Use @Query with JPQL for custom queries. Use native queries only when needed.
  • Use @EntityGraph to prevent N+1 queries in associations.
  • Use Specification for dynamic query building.
  • Always use @Transactional at the service layer, not repository.

Spring Security

  • Use SecurityFilterChain bean configuration (not WebSecurityConfigurerAdapter).
  • Use @PreAuthorize / @Secured for method-level authorization.
  • Use BCrypt for password encoding: new BCryptPasswordEncoder().
  • Configure CORS, CSRF, and session management explicitly.
  • Use OAuth2 Resource Server for JWT validation in APIs.

Hibernate / JPA

  • Use FetchType.LAZY by default on all associations.
  • Use @BatchSize or @Fetch(FetchMode.SUBSELECT) to avoid N+1.
  • Use @Version for optimistic locking on entities.
  • Use DTOs (records) for read queries. Do not expose entities in APIs.
  • Use Flyway or Liquibase for schema migrations.

Quarkus / Micronaut

  • Use for microservices and serverless where startup time matters.
  • Use compile-time DI (Micronaut) or build-time optimization (Quarkus).
  • Use reactive patterns with Mutiny (Quarkus) or Reactor (Micronaut).
  • Use native image builds with GraalVM for production deployments.

Build Tools

  • Use Gradle (Kotlin DSL) for new projects. Maven for enterprise legacy.
  • Use dependency management to unify versions across modules.
  • Use Bill of Materials (BOM) imports for consistent Spring versions.
  • Use Spotless or Checkstyle for enforced code formatting.

Logging

  • Use SLF4J facade with Logback or Log4j2 backend.
  • Use structured logging with MDC for correlation IDs.
  • Use parameterized logging: log.info("User {} created", userId).
  • Never log sensitive data (passwords, tokens, PII).

Java Patterns

Error Handling

  • Use unchecked exceptions for programming errors (IllegalArgumentException).
  • Use checked exceptions only for recoverable conditions the caller must handle.
  • Create domain exception hierarchy: AppException -> NotFoundException, etc.
  • Never catch Exception or Throwable broadly. Catch specific types.
  • Use try-with-resources for all AutoCloseable resources.

Immutability

  • Use record for immutable value objects (Java 16+).
  • Use List.copyOf(), Map.copyOf() to create unmodifiable copies.
  • Make fields private final. No setters unless mutation is required.
  • Return defensive copies of mutable collections from getters.
  • Use builder pattern for constructing immutable objects with many fields.

Optional

  • Use Optional<T> as return type for methods that may not return a value.
  • Chain: optional.map(...).orElseThrow(...). Avoid isPresent() + get().
  • Never use Optional for fields, method parameters, or collection elements.
  • Use Optional.empty() over null. Use Optional.ofNullable() at boundaries.

Streams

  • Use streams for transformations: filter, map, collect.
  • Avoid side effects in stream operations. Keep them pure.
  • Use Collectors.toUnmodifiableList() for immutable results.
  • Prefer for loop for simple iterations that do not transform data.
  • Use Stream.of() or IntStream.range() for generating sequences.

Dependency Injection

  • Use constructor injection exclusively. No field or setter injection.
  • Accept interfaces in constructors, not implementations.
  • Use @Component, @Service, @Repository for Spring-managed beans.
  • Keep the number of constructor dependencies under 5. Split if more.

Concurrency

  • Use ExecutorService and CompletableFuture for async operations.
  • Use virtual threads (Java 21+) for I/O-bound concurrent work.
  • Use ConcurrentHashMap, AtomicInteger for thread-safe operations.
  • Avoid synchronized blocks when possible -- use higher-level concurrency.
  • Use ReentrantReadWriteLock for read-heavy shared state.

Design Patterns

  • Use Strategy pattern (via interfaces) over switch/if-else chains.
  • Use Factory methods for flexible object creation.
  • Use Decorator pattern for composable behavior augmentation.
  • Avoid Singleton pattern -- use DI container for lifecycle management.

Anti-Patterns

  • Returning null from methods -- use Optional or empty collections.
  • Mutable DTOs with getters/setters -- use records.
  • God classes with 20+ dependencies -- split by responsibility.
  • String typing for domain values -- use types, enums, or value objects.

Java Security

Input Validation

  • Validate all input with Jakarta Bean Validation (@NotNull, @Size, @Email).
  • Use @Valid on controller parameters to trigger validation automatically.
  • Create custom validators for domain-specific rules.
  • Never trust client-provided IDs. Verify resource ownership server-side.

SQL Injection

  • Use JPA/Hibernate parameterized queries. Never concatenate input into JPQL/SQL.
  • Use CriteriaBuilder or Specifications for dynamic queries.
  • For native queries, use named parameters: @Query(value = "... WHERE id = :id", nativeQuery = true).
  • Use PreparedStatement if using JDBC directly. Never Statement with concatenation.

Authentication

  • Use Spring Security with BCrypt (BCryptPasswordEncoder) for password hashing.
  • Use JWT with short expiration (15 min) + refresh tokens for APIs.
  • Implement account lockout after N failed attempts.
  • Use @AuthenticationPrincipal to access the current user in controllers.

Authorization

  • Use @PreAuthorize("hasRole('ADMIN')") for role-based access control.
  • Use method security for fine-grained authorization.
  • Check resource ownership in service layer, not just role membership.
  • Default deny: require explicit authorization for every endpoint.

XSS and CSRF

  • Spring auto-escapes Thymeleaf output. Do not use th:utext with user data.
  • Enable CSRF protection for session-based auth. Disable only for stateless JWT APIs.
  • Set Content-Type headers explicitly on responses.
  • Use CSP headers to restrict script sources.

Serialization

  • Do not deserialize untrusted data with ObjectInputStream (RCE risk).
  • Use Jackson with @JsonIgnoreProperties(ignoreUnknown = true).
  • Disable default typing in Jackson: never use enableDefaultTyping().
  • Validate deserialized objects with Bean Validation after parsing.

Dependencies

  • Run OWASP Dependency-Check in CI: mvn verify -P owasp-check.
  • Update Spring Boot regularly -- security patches are frequent.
  • Use dependencyManagement to control transitive dependency versions.
  • Audit mvn dependency:tree for unexpected transitive dependencies.

Secrets

  • Use Spring Cloud Config or Vault for secrets management.
  • Use @Value("${secret}") with env var placeholders, not hardcoded values.
  • Never log request headers containing Authorization or session tokens.
  • Use separate config profiles for dev/staging/prod with different secrets.

Logging Security

  • Use parameterized logging to prevent log injection.
  • Sanitize user input before logging: remove newlines and control characters.
  • Never log stack traces to API responses. Return generic error messages.

Java Testing

Framework

  • Use JUnit 5 (Jupiter) for all new tests. No JUnit 4.
  • Use AssertJ for fluent, readable assertions.
  • Use Mockito for mocking dependencies.
  • Use Testcontainers for integration tests with databases/services.

File Naming

  • Test classes: FooTest.java in src/test/java/ mirroring source package.
  • Integration tests: FooIT.java or use @Tag("integration").
  • Test utilities: src/test/java/.../support/ or TestUtils.java.

Structure

  • Use @Nested classes to group related tests within a test class.
  • Use @DisplayName for human-readable test descriptions.
  • Use @BeforeEach for setup, @AfterEach for cleanup.
  • Use @ParameterizedTest with @ValueSource, @CsvSource, @MethodSource.

Assertions (AssertJ)

  • Use assertThat(actual).isEqualTo(expected) over JUnit assertions.
  • Use assertThatThrownBy(() -> ...).isInstanceOf(FooException.class).
  • Use assertThat(list).hasSize(3).extracting("name").contains("Ada").
  • Chain assertions for readable, self-documenting tests.

Mocking (Mockito)

  • Use @Mock + @ExtendWith(MockitoExtension.class) for injection.
  • Use when().thenReturn() for stubbing. verify() for interaction checking.
  • Use @InjectMocks to auto-inject mocks into the class under test.
  • Prefer constructor injection in production code for testability.
  • Use ArgumentCaptor to inspect complex arguments.

Integration Testing

  • Use Testcontainers for PostgreSQL, Redis, Kafka, etc.
  • Use @SpringBootTest sparingly -- it starts the full context. Prefer slices.
  • Use @WebMvcTest for controller tests, @DataJpaTest for repository tests.
  • Use @TestConfiguration for test-specific bean overrides.

Test Data

  • Use test builders or factory methods for creating test objects.
  • Use @Sql annotation to load test data from SQL files.
  • Keep test data minimal. Only set fields relevant to the behavior under test.
  • Use random UUIDs for IDs in tests to avoid collision.

Performance

  • Run tests in parallel: configure junit.jupiter.execution.parallel.enabled=true.
  • Use @SpringBootTest only when integration context is needed.
  • Mock external dependencies in unit tests for speed.
  • Keep the full test suite under 5 minutes.

版本历史

  1. v6.2.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.1.0...v6.2.0

  2. v6.1.0 GitHub ↗
    原版更新说明

    **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v6.0.0...v6.1.0

  3. v6.0.0 GitHub ↗
    原版更新说明

    ## What's Changed * chore: bump softprops/action-gh-release from 3.0.3 to 3.0.4 by @dependabot[bot] in https://github.com/softspark/ai-toolkit/pull/45 * fix: handle Windows status output and clarify Antigravity workflow support by @softspark in https://github.com/softspark/ai-toolkit/pull/46 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.5.0...v6.0.0

  4. v5.5.0 GitHub ↗
    原版更新说明

    ### Ecosystem - **OpenCode V2 and V1 compatibility:** `scripts/generate_opencode_plugin.py` emits the documented `id/setup/server` contract for V2 and V1 **1.18.29+**. Upgrade older V1 clients before using this plugin, then run `ai-toolkit update` to regenerate managed copies. `doctor` warns about obsolete V1-only exports. Scoped global/project IDs avoid native collisions; advisory work has one owner per location, while safety guards execute in every registered layer. The current V2 package is `@opencode/cli`; `opencode-ai` still publishes V1. - **Claude guard failure policy:** destructive-command, home-path and configuration guards use `onFailure: block` on Claude Code **2.1.295+**. Legacy entries migrate without duplication; hooks owned by other plugins survive. Older clients do not have this infrastructure-failure guarantee. - **Codex, Gemini and Devin:** Codex refresh accepts the two diagnostic model-request events. Gemini advisory hooks return native JSON and save native completion responses; Devin prompt/edit hooks emit event-labelled context. - **All 13 integrations reviewed:** refresh release metadata and the ecosystem snapshot, distinguish stable/preview channels, and pin Auggie's stable v0 references. User model, effort and approval selections remain unchanged. ### Fixed - **One Claude Stop checker:** remove the duplicate advisory handler from the global and app manifests. `quality-gate.sh` keeps PHPStan advisory through `quality-check.sh --php-only`, preserving checker precedence and Makefile settings. PHPStan now runs synchronously on Stop and TaskCompleted (#43). - **OpenCode guard execution:** replace the unsupported Bun stdin path with real subprocess execution in both APIs. Denial, missing guards, crashes and timeouts block tools. Transactional generation refuses user-owned collisions and symlinked destinations; lifecycle cleanup releases advisory ownership. - **Isolated release smoke:** `scripts/release.sh` installs the packed artifact in a disposable, network-disabled container with no mounts and the OS user's default home. Host settings are not used as a smoke sandbox. ### Changed - Hook entries: 29 to 28 across the same 14 Claude events. Skills remain 116 and agents remain 44. Bats coverage grows from 2012 to 2037 tests. - Refresh compatibility documentation and remove stale inventory counts from the backward-compatibility policy. All protected public surfaces remain. - Skill body budget is unchanged: the largest body remains `design-engineering` at 17,197 bytes, less than 2,000 bytes below the 18,000-byte warning threshold, so the release ratchet does not apply. **Included pull request:** [#43: run the project checker once on Claude Code Stop](https://github.com/softspark/ai-toolkit/pull/43), contributed by @jacekprzybyl. **Full changelog:** https://github.com/softspark/ai-toolkit/compare/v5.4.2...v5.5.0

  5. v5.4.2 GitHub ↗
    原版更新说明

    ## What's Changed * fix(install): read state.json on native Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/39 * test: isolate USERPROFILE together with HOME on Windows by @jacekprzybyl in https://github.com/softspark/ai-toolkit/pull/41 **Full Changelog**: https://github.com/softspark/ai-toolkit/compare/v5.4.1...v5.4.2

此处仅展示最近 5 个版本。 在原站查看完整版本历史 ↗

当前收录版本

0.0.1

核对来源版本 ↗

质量评测

满分100 · 来自 SkillPi LAB 实验室的评测报告。

场景价值85/100

亮点

  • 提供全面的 Java 编码规范,涵盖风格、框架、安全、测试等关键领域
  • 适用于广泛的 Java 开发者,具有明确的实用价值和通用性
触发精准90/100

亮点

  • 触发条件明确列出 .java、pom.xml、build.gradle 等文件类型及 Spring、JUnit 等关键词
  • 覆盖合理,边界清晰
结构规范90/100

亮点

  • 文档结构清晰,分章节覆盖 Style、Frameworks、Patterns、Security、Testing
  • 每部分有具体条目和示例,frontmatter 完整
执行可靠85/100

亮点

  • 内容为静态规则文档,无动态执行逻辑,工具来源为通用 Java 生态标准
  • 参数建议合理,覆盖主要异常处理和安全实践
证据可验 (前四项均值)88/100

取前四项原始分值的算术平均,四舍五入取整。可通过收录报告核对各项评分与说明,运行记录需单独查证。

正文静态检测

100 / 100 · skillpi-20261123-no-r3-v1

正文未命中当前规则。

分数仅反映正文中的规则命中,供使用前参考。附件与运行行为不在此评分范围内。

权限与使用前检查

根据当前主文档自动整理,命中内容可能是示例或防护说明;不是实际权限声明,也未覆盖附件、外部依赖或运行行为。

未从主文档识别到上述常见操作,不能据此判断无需权限或没有风险。

本站展示提示不会授予权限。涉及文件改动、密钥、外部发送或费用时,仍由你使用的工具按需确认。

安全评级与访问范围

safe · 静态证据核验,不代表运行安全保证。

使用前请由宿主核对并授权实际文件读写、外部服务和联网目的地;本站的核验不会授予任何运行权限。