开发者

How to create recursive object graphs with Guice?

开发者 https://www.devze.com 2023-04-05 07:41 出处:网络
Suppose I have 5 classes A, B, C, D, E that all implement a common interface X. Each of the classes B, C, D and E has a field of type X (so they can be seen as wrapper classes).

Suppose I have 5 classes A, B, C, D, E that all implement a common interface X. Each of the classes B, C, D and E has a field of type X (so they can be seen as wrapper classes).

Which instances are created is determined at runtime, so I could have for example one of the following object graphs:

E -> D -> C -> B -> A
D -> B -> A
E -> A
A

(The order is fixed and the innermost instance is always of type A, but otherwise there are no restrictions.)

No I'd like to create this objects with Guice to avoid providing all their other dependencies by hand.

What's the easiest way to do this? Currently it seems that I have to

  1. let Guice create instance of A
  2. create a module that binds X.class to this instance and a child injector with this additional module
  3. let Guice create the next instance (e.g., of type B)
  4. repeat 2., now binding X.class to the instance of B
  5. repeat 3. and 4. until all objects are created

Is there an easier way? Could I perhaps somehow automatically register a new instance of a subclass of X as a binding for X each time it is created?

Edit: Clarification of "Which instances are created is determined at runtime":

My current code looks like this:

X createX() {
开发者_Go百科  X x = new A(dependencies);
  if (useB) x = new B(x, some, dependencies);
  if (useC) x = new C(x, further, dependencies);
  if (useD) x = new D(x, dependency);
  if (useE) x = new E(x, yet, other, dependencies);
  return x;
}

The value of the flags useB, useC, useD, and useE comes from a properties file.

My main goal is to save providing all the dependencies to the constructors manually.

Edit: Solution:

I have added my own solution which I have found in the meantime. Thanks to all answerers!

A way to improve my solution would be to make it possible to remove the @InInstance annotation on the constructor parameters. I have experimented with type listeners, but I haven't found a way to do this. Hints would be welcome.


I have developed the following solution to the problem:

First, I create a marker annotation @InInstance, which takes a Class object as value. I use this annotation to annotate the parameters of type X in all wrapper classes (i.e., B to E). Example:

class B {
  B(@InInstance(B.class) X x,
    Other dependencies) {
  ...
  }
}

Now if I want for example an instance of the full chain (A to E), I bind

  • X.class to E.class
  • X.class annotatedWith InInstance(E.class) to D.class
  • ...
  • X.class annotatedWith InInstance(B.class) to A.class

and then call createInstance(X.class).

This solves the problem of letting Guice create my instances and provide the dependencies.

Now for the problem of creating the appropriate bindings at runtime according to the properties file, I created a Guice extension that allows me to create "wrapper bindings". Such a binding takes a type (here X), a wrapper implementation type (here one of B to E) and a base module, which needs to contain a binding for X. It then creates a new module that contains two bindings:

  • the same binding for X as in the base module, but annotatedWith(InInstance(wrapper type))
  • a binding from X to the wrapper type

Such a module can then be used to override the bindings of the base module with Modules.override(base module).with(wrapper module).

With some nice Guice-style EDSL, this looks like:

Module baseModule = ... // contains binding for X to A

if (useB) {
  Module wrapperModule = new ChainingModule() {
    void configure() {
      wrap(X.class).from(baseModule).with(B.class); // possible to use .in(...) etc. here
      // In this case, this line is equivalent to

      // bind(X.class).annotatedWith(InInstance(B.class)).to(A.class);
      // bind(X.class).to(B.class);

      // It has the advantage of automatically looking up the current binding
      // for X in the base module, which makes it easy to chain this.
    }
  }
  baseModule = Modules.override(baseModule).with(wrapperModule);
}

...

And with some helper methods for common cases it looks like:

Module module = ... // contains binding for X to A
if (useB) {
  module = Chaining.wrap(X.class).from(module).with(B.class);
}
if (useC) {
  module = Chaining.wrap(X.class).from(module).with(C.class);
}
if (useD) {
  module = Chaining.wrap(X.class).from(module).with(D.class);
}
if (useE) {
  module = Chaining.wrap(X.class).from(module).with(E.class);
}

Injector injector = Guice.createInjector(module);
X x = injector.createInstance(X.class);

Each line creates the appropriate wrapper module and returns a new module containing the given module with some bindings overriden by the wrapper module.


"At Runtime" adds quite a bit of complexity. I assume that means for each X instance you create, you make some decision about the chain of objects wrapping A.

How about if you don't inject X into E, D, C & B, during construction? Instead, add setNext(X) method. I'm not sure how realistic that is for you, but hear me out. You could create a factory like the following:

class XFactory {
  @Inject Provider<A> a;
  @Inject Provider<B> b;
  @Inject Provider<C> c;
  @Inject Provider<D> d;
  @Inject Provider<E> e;
  public X create(Data state) {
    // the 'state' object is just whatever information you use to 
    // decide what objects you need to create;
    X result = a.get();
    if(state.useB()) {
      B head = b.get();
      head.setNext(result);
      result = head;
    }
    if(state.useC()) {
      C head = c.get();
      head.setNext(result);
      result = head;
    }
    if(state.useD()) {
      D head = d.get();
      head.setNext(result);
      result = head;
    }
    if(state.useE()) {
      E head = e.get();
      head.setNext(result);
      result = head;
    }
    return result;
  }
}

You could consider introducing an interface like DelegatingX or WrapperX to hold the setNext() method. It might reduce some of the repetition.

Also, if "at runtime" is actually application boot, and therefore each instance of X should be the same chain of objects, then you have an additional option:

class MyModule extends AbstractModule {
  public void configure() {
    Multibinder<DelegatingX> chain
        = Multibinder.newSetBinder(binder(), DelegatingX.class);
    if(useB()) chain.addBinding().to(B.class);
    if(useC()) chain.addBinding().to(C.class);
    if(useD()) chain.addBinding().to(D.class);
    if(useE()) chain.addBinding().to(E.class);
  }
  @Provides X provideX(Set<DelegatingX> chain, A a) {
    X result = a;
    // 'item' is B, then C...
    for(X item : chain) {
      item.setNext(result);
      result = item;
    }
    return result; // this is E
  }
}

I know this answer is pretty abstract, but I hope it gets you a little bit closer to a solution.


I also find the "at runtime" part of your definition unclear.

But let's say we start by imagining how these chains are made without Guice.

class chainHolder {
  public final X chain1 = new E(new D(new C(new B(new A()))));
  public final X chain2 = new D(new B(new A()));
  public final X chain3 = new E(new  A());
  public final X chain4 = new A();
}

But your problem is that there's a lot of other stuff to pass into each constructor that you'd like to have injected? Okay let's setup some injection for these instead:

//Pseudo multi-class def here
classes B...E extends X {
  private final X nextInChain;
  @Inject
  public B...E(TheStuffINeedToo NotMentionedAbove, X nextInChain) {
    super(TheStuffINeedToo);
    this.nextInChain = nextInChain;
  }
}

class A extends X {
  @Inject
  public A(TheStuffINeedToo NotMentionedAbove) {
    super(TheStuffINeedToo);
  }
}

class chainHolder {
  public final X chain1;
  public final X chain2;
  public final X chain3;
  public final X chain4;
  @Inject
  public chainHolder(@Chain1 X c1, @Chain2 X c2, @Chain3 X c3, @Chain4 X c4) {
    chain1 = c1;
    chain2 = c2;
    chain3 = c3;
    chain4 = c4;
  }
}

class chainModlule extends AbstractModule {
  public void configure() {
    //The other stuff you wanted provided gets bound here.
    bind(TheStuffINeedToo.class).to(TheStuffNotMentionedInTheQuestion.class);
    //Maybe A should always be the same terminating instance.
    bind(A).in(Singleton.class);
    bind(X).annotatedWith(Chain4.class).to(A.class);
  }

  @Provides @Chain1
  public X providesChain1X(@Chain1 Provider<E> e) {
    return e.get();
  }

  @Provides @Chain1
  public E providesChain1E(@Chain1 Provider<D> d, TheStuffINeedToo stuff) {
    return new E(stuff, d.get());
  }

  @Provides @Chain1
  public D providesChain1D(@Chain1 Provider<C> c, TheStuffINeedToo stuff) {
    return new D(stuff, c.get());
  }

  @Provides @Chain1
  public C providesChain1C(@Chain1 Provider<B> b, TheStuffINeedToo stuff) {
    return new C(stuff, b.get());
  }

  @Provides @Chain1
  public B providesChain1B(Provider<A> a, TheStuffINeedToo stuff) {
    return new B(stuff, a.get());
  }

 // ... Similarly for chain2 then ...

  @Provides @Chain3
  public X providesChain3X(@Chain3 Provider<E> e) {
    return e.get();
  }

  @Provides @Chain3
  public E providesChain3E(Provider<A> a, TheStuffINeedToo stuff) {
    return new E(stuff, a.get());
  }
}

Now. You see that's not saving /a lot/ of work. If all the classes take in the same stuff you wanted injection to do for you (like my pseudo setup does) then you could roll the whole chain into one provider and reuse that stuff instance, or a provider for the stuff.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号