javaspring-bootdependency-injectionmapstruct

How to use constructor injection in Mapstruct's mapper?


In some mapper classes, I need to use an autowired ObjectMapper to transform String to JsonNode or verse-vera. I can acheive my goal by using the field injection with @autowired. But it's not suitable for unit test so I'd like to try using the constructor injection.

My current working code with the field injection:

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

I try to convert it to the constructor injection so I can provide constructor argument in my unit test:

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

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

But I get a Constructor in CustomMapper cannot be applied to the given type error during compilation. How do I fix it? Or is there other better way to map String to JsonNode in Mapstruct?


Solution

  • Constructor injection cannot be used in the mapper definition. Only in the mapper implementation.

    However, for unit testing I'd suggest that you use setter injection.

    Your mapper will then look like:

    @Mapper( componentModel = "spring") 
    public class CustomMapper {
    
        protected ObjectMapper mapper;
    
    
        @Autowired
        public void setMapper(ObjectMapper mapper) {
            this.mapper = mapper;
       } 
    
    }