问题
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