Search code examples
guiceorika

How to inject an Orika FactoryMapper impl using Google Guice?


Using Google Guice, how do I inject an implementation of Orika's MapperFactory?

private MapperFactory mf = new DefaultMapperFactory.Builder().build();

i.e. the default constructor is not accessible and you need to use the builder.


Solution

  • In your Module, use bind() to register the built instance:

    bind(MapperFactory.class).toInstance(new DefaultMapperFactory.Builder().build());
    

    or use a @Provides method:

    @Provides
    public MapperFactory mapperFactory() {
       new DefaultMapperFactory.Builder().build();
    }
    

    with the first approach, you get a singleton, so every time you inject a MapperFactory, you get the same instance, in the second case, every time you inject, you get a freshly built copy.