How can i combine Guice and Mapstruct?

若如初见. 提交于 2021-01-28 05:50:34

问题


I'm using jersey and Guice DI and I want to use Mapstruct interfaces with @Inject annotation. So is there some way to force Guice to autowire Mapstruct interface implementations ?


回答1:


You can configure the implementations of the Mappers to be annotated with JSR 330 annotation by using @Mapper(componentModel = "jsr330"). You can find more information in the reference documentation.

You can then bind the Mapper interface with the implementation class in your modules.

One way to bind them is to use Guice Linked Bindings:

bind(MyDtoMapper.class).to(MyDtoMapperImpl.class)

Another way to bind them is to use Instance Bindings:

bind(MyDtoMapper.class).toInstance(MyDtoMapper.INSTANCE)



回答2:


Ran into issues with using Guice and the jsr330 componentModel, though I don't recall what they were exactly. My use case was a bit more complex because I needed to pass in another service to a mapper decorator as well. Should work for your simple case as well. Ended up doing provider methods in the Guice Module, like so:

public YourModule  extends AbstractModule {
    //With Decorator
    @Provides
    @Singleton
    FooMapper providesFooMapper(RequiredService requiredSvc) {
        FooMapper mapper = Mappers.getMapper(FooMapper.class);
        ((FooMapperDecorator) mapper).setRequiredService(requiredSvc);
        return mapper;
    }

    //Simple Mapper with no dependencies
    @Provides
    @Singleton
    BarMapper providesBarMapper() {
        return Mappers.getMapper(BarMapper.class);
    }
}

Works without a hitch, though I would like for the simple case to be handled by MapStruct cleanly at some point. I'll also note that I only use constructor injection; should work the same for setter injection but YMMV.




回答3:


Thx @Filip. So yeah @Mapper(componentModel = "jsr330") almost made all work only thing I had to create binding for each mapper that I use directly in my code bind(MyDtoMapper.class).toInstance(MyDtoMapper.INSTANCE) and INSTANCE is declared in MyDtoMapper interface this way: MyDtoMapper INSTANCE = Mappers.getMapper( MyDtoMapper.class );



来源:https://stackoverflow.com/questions/43369852/how-can-i-combine-guice-and-mapstruct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!