MCPInstall

mapstruct-patterns

MapStruct 最佳实践模式。从官方 Reference Guide 提炼,覆盖 Mapper 三种定义方式(接口/抽象类/default方法)、Spring 注入策略(CONSTRUCTOR推荐/SETTER解决循环依赖)、嵌套映射模式(显式子方法 dot notation 一次性配置)、@Qualifier @Named 的安全选择、Lombok 集成规则、@MappingComposition 谨慎使用。 纠正 LLM 最常见的错误:用反射 BeanUtils 而非编译期 MapStruct、嵌套映射全写在一个方法、不知 SETTER 解决循环依赖。

Installs
97
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/full-stack-skills/java-skills --skill mapstruct-patterns
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads mapstruct-patterns automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

MapStruct 最佳实践模式

来源: MapStruct Reference Guide | GitHub: mapstruct/mapstruct

Capability Boundaries

✅ Strong Suits

  1. Mapper 三种定义方式 — 接口(标准) / 抽象类(需要字段) / default方法(自定义逻辑)
  2. Spring 注入策略 — CONSTRUCTOR(推荐,测试友好) / SETTER(解决循环依赖)
  3. 嵌套映射模式 — 显式子方法封装(推荐) > dot notation 一次性配置
  4. @Qualifier vs @Named — 自定义 @Qualifier 注解(IDE重构安全) > @Named(字符串不安全)
  5. Lombok 集成 — annotationProcessorPaths 中 Lombok 必须在 MapStruct 之前
  6. @MappingComposition — 组合注解复用,但 error messages 不成熟需谨慎

❌ Out of Scope

  1. 运行时动态 Bean 映射(Orika/Dozer) → MapStruct 编译期生成,不是反射

核心模式

模式 1: Spring 注入策略选择

// ✅ 推荐:CONSTRUCTOR 注入(测试友好,不依赖Spring容器)
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface UserMapper { UserVO toVO(User e); }

// ✅ 循环依赖:SETTER注入
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.SETTER,
        uses = { OrderMapper.class })
public interface UserMapper { ... }

// ✅ 全局默认配置(避免每个接口重复)
@MapperConfig(componentModel = "spring", injectionStrategy = InjectionStrategy.CONSTRUCTOR)
public interface CentralConfig {}
@Mapper(config = CentralConfig.class) public interface UserMapper { ... }

模式 2: 嵌套映射的正确方式

// ❌ 反模式:全写在顶层(重复配置,难以维护)
@Mapping(target = "address.street", source = "home.street")
@Mapping(target = "address.city", source = "home.city")
UserDTO toDTO(User e);

// ✅ 模式:显式子方法(单一配置点,可复用)
@Mapper
public interface UserMapper {
    UserDTO toDTO(User e);               // MapStruct 自动检测嵌套类型
    AddressDTO toAddressDTO(Address e);   // 子映射方法 — 唯一配置处
}

// ✅ dot notation + 子方法组合(局部覆盖)
@Mapping(target = "address.zip", constant = "00000")  // 常量覆盖
@Mapping(target = "address", source = "homeAddr")     // 其余走子方法
UserDTO toDTO(User e);

模式 3: @Qualifier > @Named

// ✅ 推荐:自定义 @Qualifier(IDE重构安全)
@Qualifier @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS)
public @interface ToUpperCase {}
@ToUpperCase default String toUpper(String s) { return s.toUpperCase(); }
@Mapping(target = "name", qualifiedBy = ToUpperCase.class)
UserDTO toDTO(User e);

// ⚠️ 可用但不推荐:@Named(字符串依赖,IDE不能自动重命名)
@Named("toUpper") default String toUpper(String s) { return s.toUpperCase(); }
@Mapping(target = "name", qualifiedByName = "toUpper")  // 字符串引用

模式 4: 循环依赖的 Spring 配置

// 场景: UserMapper → OrderMapper → UserMapper
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.SETTER,
        uses = { OrderMapper.class })  // ← SETTER是关键
public interface UserMapper {
    @Mapping(target = "orders", source = "orderList")
    UserDTO toDTO(User entity);
}
@Mapper(componentModel = "spring", injectionStrategy = InjectionStrategy.SETTER,
        uses = { UserMapper.class })
public interface OrderMapper { ... }

模式 5: 抽象类 Mapper

@Mapper
public abstract class UserMapper {
    @Autowired protected PasswordEncoder encoder;  // 可注入字段
    @Mapping(target = "encodedPwd", expression = "java(encoder.encode(dto.getPassword()))")
    public abstract UserVO toVO(UserDTO dto);
    protected String formatDate(LocalDateTime dt) { return dt.format(FORMATTER); } // 自定义方法
}

Gotchas

  1. Lombok 的 annotationProcessor 必须在 MapStruct 之前 — 否则编译期找不到 getter/setter
  2. CONSTRUCTOR 注入遇循环依赖会编译失败 — 改为 SETTER
  3. dot notation 不创建子映射方法 — 嵌套字段逻辑重复时用显式子方法
  4. MapStruct 编译期生成,性能等同手写代码 — 不是反射
  5. @Named 字符串引用不安全 — IDE重构不会自动更新,用自定义 @Qualifier
  6. CollectionMappingStrategy.DEFAULT 不要显式使用 — 仅作内部区分
  7. Mapper 接口中 default 方法优先于生成代码 — 可用于自定义转换逻辑

Data Privacy

本技能不收集、存储或传输任何用户数据。

FAQ

What does the mapstruct-patterns skill do?

MapStruct 最佳实践模式。从官方 Reference Guide 提炼,覆盖 Mapper 三种定义方式(接口/抽象类/default方法)、Spring 注入策略(CONSTRUCTOR推荐/SETTER解决循环依赖)、嵌套映射模式(显式子方法 dot notation 一次性配置)、@Qualifier @Named 的安全选择、Lombok 集成规则、@MappingComposition 谨慎使用。 纠正 LLM 最常见的错误:用反射 BeanUtils 而非编译期 MapStruct、嵌套映射全写在一个方法、不知 SETTER 解决循环依赖。

How do I install mapstruct-patterns?

Run npx skills add https://github.com/full-stack-skills/java-skills --skill mapstruct-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/mapstruct-patterns/ (personal) or .claude/skills/mapstruct-patterns/ (project).

Which AI agents can use mapstruct-patterns?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is mapstruct-patterns safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains mapstruct-patterns?

It is published by full-stack-skills in full-stack-skills/java-skills. It has 97 recorded installs.

More from full-stack-skills/java-skills

View all →

mybatis-plus-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs114 installs

java-code-comments

full-stack-skills/java-skills

Provides comprehensive guidance for adding Java code comments following industry standards and best practices. This skill helps add class-level comments, method-level comments, and field-level comments to Java code. Use when the user wants to add comments to Java code, needs to document Java classes/methods/fields, wants to improve code documentation, or needs to generate JavaDoc comments. This skill covers Controller, Service, ServiceImpl, Mapper, Model, Entity, BO (Business Object), DTO, VO, and other common Java component types. The skill follows a systematic workflow: scan codebase, identify components, create todo list, and add comments in order (class comments → method comments → field comments).

Backend & APIs112 installs

mybatis-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs102 installs

java-development-manual

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs94 installs

redis-redisson-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Data & Databases93 installs

junit-mockito-patterns

full-stack-skills/java-skills

Open the skill to read its SKILL.md instructions.

Backend & APIs93 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs