Search code examples
guiceauto-value

Is it possible to use @AutoValue with Guice's FactoryModuleBuilder?


Per https://github.com/google/guice/wiki/AssistedInject,

Lets say I have an interface A, implementing class AImpl and another interface AFactory that I use with the FactoryModuleBuilder -

..

install(new FactoryModuleBuilder()
    .implement(A.class, AImpl.class)
    .build(AFactory.class)
);

..

Is it possible to use AutoValue for AImpl? My concern is then AImpl would be abstract and the factory module won't be able to instantiate it. And if I pass AutoValue_AImpl instead to the factory module, it won't have the @Assisted* annotations on it.


Solution

  • These packages don't work well together; more to the point, there is no reason you should use these two features together.

    AutoValue typically creates data objects or value objects, with robust equals and hashCode implementations. Objects created from AutoValue are immutable, with static factory methods instead of constructors; there's no room or reason for Guice-provided dependencies. See the docs:

    Using AutoValue limits your public creation API to static factory methods, not constructors. See Effective Java Item 1 for several reasons this is usually a good idea anyway.

    AutoValue does not and will not support creating mutable value types. (We may consider adding support for withField-style methods, which return a new immutable copy of the original instance with one field value changed.)

    FactoryModuleBuilder typically creates factories for objects that have some injected dependencies and some manually-specified dependencies. As above, AutoValue packages should never fit this description.

    Of course, you may use constants accessible from Guice to build out your value objects; however, you'll need to do this by writing your own lightweight factory object that maps injectable parameters to your value object's methods as needed.