You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MapStruct中使用Spring Boot的@Conditional注解

在MapStruct Bean上使用Spring Boot @Conditional注解的实现方案

MapStruct生成的Spring Bean可以通过以下两种方式结合@Conditional系列注解,实现配置文件控制Bean创建的需求:

方法一:直接使用Spring自带的@ConditionalOnProperty注解

这是最常用的场景,针对简单的配置属性判断需求,直接在MapStruct的Mapper接口上添加该注解即可。MapStruct会自动将接口上的Spring注解传递到生成的实现类中,Spring容器会根据配置属性决定是否创建该Bean。

示例代码:

// Mapper接口
@Mapper(componentModel = "spring") // 指定生成Spring管理的Bean
@ConditionalOnProperty(
    name = "user.mapper.enabled", 
    havingValue = "true", 
    matchIfMissing = false // 配置缺失时不创建Bean
)
public interface UserMapper {
    UserDto toDto(User user);
}

对应配置文件(application.yml):

user:
  mapper:
    enabled: true # 设置为false时,该Mapper Bean不会被创建

方法二:自定义Condition实现复杂判断

如果需要更复杂的条件逻辑(比如多属性组合判断、环境变量判断等),可以自定义Condition类,再通过@Conditional注解绑定到Mapper接口上。

步骤1:自定义Condition类

public class UserMapperCondition implements Condition {
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        Environment env = context.getEnvironment();
        // 这里可以编写任意复杂的判断逻辑,比如多属性组合
        boolean isEnabled = "true".equals(env.getProperty("user.mapper.enabled"));
        boolean isProdEnv = "prod".equals(env.getProperty("spring.profiles.active"));
        return isEnabled && isProdEnv;
    }
}

步骤2:在Mapper接口上绑定自定义Condition

@Mapper(componentModel = "spring")
@Conditional(UserMapperCondition.class) // 使用自定义的条件判断类
public interface UserMapper {
    UserDto toDto(User user);
}

关键注意事项

  • 确保使用的MapStruct版本在1.4及以上,该版本开始支持将接口上的Spring注解传递到生成的实现类中。
  • 如果项目中使用@MapperScan扫描Mapper接口,需保证扫描范围包含目标Mapper,否则注解无法生效。
  • 测试时可通过ApplicationContext.getBean(UserMapper.class)验证,当条件不满足时会抛出NoSuchBeanDefinitionException,说明Bean未被创建。

内容的提问来源于stack exchange,提问作者Muhammed K K

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 00:54:58