Search code examples
javamapstruct

using mapstruct with service


I have the following Mapper:

@Mapper(componentModel = "spring",
    nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface StudentMapper {

    StudentMapper MAPPER = Mappers.getMapper( StudentMapper.class );

    @Mapping(target = "id", ignore = true)
    Student map(Map<String, Object> map, @MappingTarget Student student);

}

This is my StudentService which uses the MAPPER:

import static com.test.StudentMapper.MAPPER;

public class StudentService {
    public void update(final @Valid Map<String, Object> map, Student student) { 
        Student result = MAPPER.map(map, student);
    }
}

When I run my tests:

I am getting java.lang.NullPointerException: Cannot invoke map(Object) because "this.qualifier" is null

How can I inject Qualifier properly when I use the mapper in my StudentService class?


Solution

  • Since you are using

    componentModel = "spring"
    

    i would suggest that you simply inject the mappers like normal dependencies via dependency injection.

    @Service
    @RequiredArgsConstructor
    public class StudentService {
    
        private final StudentMapper studentMapper;
    
        public void update(final @Valid Map<String, Object> map, Student student) { 
            Student result = MAPPER.updateStudentFromMap(map, student);
        }
    }
    

    I am not sure the code you provided is a viable way to use mapstruct.

    public interface StudentMapper {
    
    StudentMapper MAPPER = Mappers.getMapper( StudentMapper.class );