Feature Request Guice automatically builder pattern

323 views
Skip to first unread message

Kyle Roush

unread,
Feb 26, 2019, 4:57:17 PM2/26/19
to google-guice
I would like to use a builder (preferably auto-value)  with Guice.
Guice can find constructors annotated with @Inject but those can be cumbersome to maintain and I would like to move to a builder pattern and have that be automatically found.

so the current way is like
class ExampleA {

  ...

  @Inject
  public ExampleA(A a, B b, ...) {

  }


  ...


}

But I would like to be able to
@ProvidedBy(builder = Builder.class) // or some way to let know guice to know what is the thing that builds it
@AutoValue
class
ExampleB {
  ...

  @AutoValue.Builder
 
public abstract static class Builder {

     public abstract Builder setA(A a);

    
public abstract Builder setB(B a);

     ...

     public abstract
ExampleB build();
 
}


}




Right now the only way i can think of how to use a builder pattern with Guice is to have a provides method int he module and have all the possible inputs injected in to the method of the provides which can still be very annoying to maintain

I am open to different ideas on how to link the builder and real object.


Thomas Broyer

unread,
Feb 27, 2019, 5:06:46 AM2/27/19
to google-guice
Would that work?

@ProvidedBy(AutoValue_ExampleB.Builder.class)
@AutoValue
abstract class ExampleB {
 



 
@AutoValue.Builder
 
abstract static class Builder implements Provider<ExampleB> {
   
@Inject abstract Builder setA(A a);
   
@Inject abstract Builder setB(B b);
   

   
abstract ExampleB get();
 
}
}


That said: AutoValue has been designed for "value objects", and you're kind-of "abusing" it here as a "generic generator of builders".
(I also don't see how this is less cumbersome to maintain than a constructor; where your IDE can generate the constructor argument from a declared final field).
Reply all
Reply to author
Forward
0 new messages