【问题标题】:MapStruct and ImmutablesMapStruct 和不可变对象
【发布时间】:2020-10-29 14:27:23
【问题描述】:

我无法让 mapstruct 和不可变对象正常工作。

@Value.Immutable
public abstract class FoobarValue {
    public abstract Integer foo();
}
@Value.Immutable
public abstract class TargetFoo {
    public abstract Integer foo();
}
@Mapper
public interface ImmutableMapper {

    ImmutableMapper INSTANCE = Mappers.getMapper(ImmutableMapper.class);

    public TargetFoo toTarget(FoobarValue foobarValue);
}

要测试的主类

public class FoobarValueMain {
    public static void main(String... args) {
        FoobarValue value = ImmutableFoobarValue.builder()
                .foo(2)
                .build();
        ImmutableMapper mapper = ImmutableMapper.INSTANCE;
        System.out.println(mapper.toTarget(value).foo());
    }
}

我得到的错误是

Exception in thread "main" java.lang.IllegalStateException: Cannot build TargetFoo, some of required attributes are not set [foo]
    at org.play.ImmutableTargetFoo$Builder.build(ImmutableTargetFoo.java:158)
    at org.play.ImmutableMapperImpl.toTarget(ImmutableMapperImpl.java:21)
    at org.play.FoobarValueMain.main(FoobarValueMain.java:12)

我的build.gradle如下

ext {
    mapstructVersion = "1.4.0.Beta2"
    immutablesVersion = "2.8.2"
}

dependencies {
    annotationProcessor "org.immutables:value:$immutablesVersion" // <--- this is important
    annotationProcessor "org.mapstruct:mapstruct-processor:1.4.0.Beta2"

    compileOnly "org.immutables:value:$immutablesVersion"
    implementation "org.mapstruct:mapstruct:${mapstructVersion}"

    testCompile group: 'junit', name: 'junit', version: '4.12'
}

根据reference,这一切都应该开箱即用。我在这里错过了什么?

【问题讨论】:

    标签: gradle mapstruct immutables-library


    【解决方案1】:

    它不起作用的原因是因为您没有使用JavaBean约定。

    你需要在你的方法前加上get

    例如

    @Value.Immutable
    public abstract class TargetFoo {
        public abstract Integer getFoo();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 2011-11-05
      • 1970-01-01
      相关资源
      最近更新 更多