如何在Mapstruct的mapper中使用构造函数注入?

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

[在某些映射器类中,我需要使用自动连接的ObjectMapper来将String转换为JsonNode或反之。通过使用@autowired的场注入,可以实现我的目标。但这不适合单元测试,因此我想尝试使用构造函数注入。

我当前使用字段注入的工作代码:

@Mapper(componentModel = "spring")
public class CustomMapper {
  @autowired
  ObjectMapper mapper;
}

我尝试将其转换为构造函数注入,以便可以在单元测试中提供构造函数参数:

@Mapper(componentModel = "spring")
public class CustomMapper {
  ObjectMapper mapper;

  public CustomMapper(ObjectMapper mapper) {
    this.mapper = mapper;
  }
}

但是在编译过程中出现Constructor in CustomMapper cannot be applied to the given type错误。我如何解决它?还是在Mapstruct中还有其他更好的方法将String映射到JsonNode

java spring-boot dependency-injection mapstruct
2个回答
0
投票

构造函数注入不能在映射器定义中使用。仅在映射器实现中。

但是,对于单元测试,我建议您使用二传手进样。

您的映射器将如下所示:

@Mapper( componentModel = "spring") 
public class CustomMapper {

    protected ObjectMapper mapper;


    @Autowired
    public void setMapper(ObjectMapper mapper) {
        this.mapper = mapper;
   } 

} 

0
投票

您可以这样操作:

@Mapper(componentModel = "spring")
@RequiredArgsConstructor //lombok annotation, which authowire your field via constructor
public class CustomMapper {
  private final ObjectMapper mapper;
}

但是您仍然可以通过字段来完成。在两种情况下,您都应该在测试中模拟它。只要记住使用@InjectMocks

public CustomMapperTest {
   @InjectMocks
   private CustomMapper customMapper;
   @Mock
   private ObjectMapper objectMapper

   @BeforeEach
   void setUp() {
      customMapper= new CustomMapperImpl();
      MockitoAnnotations.initMocks(this);
      when(objectMapper.map()).thenReturn(object);
   }

   @Test
   void shouldMap() {
      Object toObject = customerMapper.map(fromObject);
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.