Mapstruct spring @ConditionalOnProperty @Conditional

问题描述 投票:0回答:1

我有一个接口 EntityMapper 和其他几个扩展它的接口,如 EntityAMapperEntityBMapperEntityCMapper 等。每个子接口都用注释

@Mapper(config = EntityMapperConfig.class)
@ConditionalOnProperty(value = "propKey", havingValue = "propValue")
,其中 EntityMapperConfig 是:

@MapperConfig(componentModel = SPRING, mappingInheritanceStrategy = AUTO_INHERIT_FROM_CONFIG)
public interface EntityMapperConfig {
}

propValue
对于每种类型都有唯一的值 EntityAMapperEntityBMapperEntityCMapper

我需要在 Spring 上下文中最多存在一个(且只有一个)实现接口 EntityMapper 的 bean:根据 propKey 的值,其类型将是 EntityAMapperEntityBMapperEntityCMapper 等。

如何实现这一目标? 是否可以让Mapstruct用@ConditionalOnProperty注释每个子类实现(EntityAMapperImplEntityAMapperImplEntityAMapperImpl等...)?

感谢您的帮助!

spring mapstruct
1个回答
0
投票

从 MapStruct 1.6.0.Beta1 开始,有一个新的注释

@AnnotateWith
,它允许您将注释传递给生成的代码。

根据您的情况,您可以执行以下操作:

@Mapper(config = EntityMapperConfig.class)
@AnnotateWith(value = ConditionalOnProperty.class, elements = [
    @AnnotateWith.Element(name = "value", strings = "propKey"),
    @AnnotateWith.Element(name = "havingValue", strings = "propAValue")
]}
public interface EntityAMapper extends EntityMapper {

}

@Mapper(config = EntityMapperConfig.class)
@AnnotateWith(value = ConditionalOnProperty.class, elements = [
    @AnnotateWith.Element(name = "value", strings = "propKey"),
    @AnnotateWith.Element(name = "havingValue", strings = "propBValue")
]}
public interface EntityBMapper extends EntityMapper {

}

@Mapper(config = EntityMapperConfig.class)
@AnnotateWith(value = ConditionalOnProperty.class, elements = [
    @AnnotateWith.Element(name = "value", strings = "propKey"),
    @AnnotateWith.Element(name = "havingValue", strings = "propCValue")
]}
public interface EntityCMapper extends EntityMapper {

}

这将生成如下代码:

@Component
@ConditionalOnProperty(value = "propKey", havingValue = "propAValue")
public class EntityAMapperImpl implements EntityAMapper {

}

@Component
@ConditionalOnProperty(value = "propKey", havingValue = "propBValue")
public class EntityBMapperImpl implements EntityBMapper {

}

@Component
@ConditionalOnProperty(value = "propKey", havingValue = "propCValue")
public class EntityCMapperImpl implements EntityCMapper {

}
© www.soinside.com 2019 - 2024. All rights reserved.