Mapstruct: NullPointerException on Mapper reaching for EntityFactory

Created on 5 Sep 2017  路  4Comments  路  Source: mapstruct/mapstruct

@Component
public class EntityFactory {...}

@Mapper(componentModel = "spring", uses = {EntityFactory.class})
public interface EntityMapper {...}

Generates:

@Component
public class EntityMapperImpl implements EntityMapper {
    @Autowired
    private EntityFactory entityFactory;

   protected Entity dtoToEntity(Dto dto) {
        if (dto == null) {
            return null;
        } else {
            Entity entity = this.entityFactory.createEntity(); <-------- NullPointerException
            entity.setValue(dto.getValue());
            entity.setKey(dto.getName());
            return entity;
        }
    }
}

Most helpful comment

@cfdobber Can you show us your spring configuration. It looks like Spring is either not injecting the entityFactory (which is strange because it needs to fail if there is none) or you are not autowiring the mapper and using it like that.

How does the call side of your mapper look like?

All 4 comments

@cfdobber Can you show us your spring configuration. It looks like Spring is either not injecting the entityFactory (which is strange because it needs to fail if there is none) or you are not autowiring the mapper and using it like that.

How does the call side of your mapper look like?

Thx for the quick answer. That made me think.
It's probably because I use:
EntityMapper INSTANCE = Mappers.getMapper(EntityMapper.class);
And then off course it isn't injected. Going to try it now.

@cfdobber that is why it is null. Mappers.getMapper(Class) should only be used with the default componentModel. You should inject the EntityMapper via Spring if you want to use Spring or use the default model otherwise.

Btw. I edited your message in order to have nice code wrapping

Thx again. Now of course it works. I was just looking at the wrong place all the time.

Was this page helpful?
0 / 5 - 0 ratings