Using Guice in a method that builds something using "this"

41 views
Skip to first unread message

adrien....@live.fr

unread,
Dec 19, 2014, 1:31:31 PM12/19/14
to google...@googlegroups.com
Hello all.

Lets say I have:

class A {
//...
}

class B {
    A getA
() {
       
// Building a A using B attributes
   
}
//...
}

I'd love to write:

class B {
   
private final a;

   
@Inject
   
private B(A a) {
       
this.a = a;
   
}
//...
}

But, since the building of the A instance relies on some data from B, I can not.
Typical exemple would be two classes mapping two SQL tables, where getA() is following a foreign key.

Is there a way Guice can be used around here? (Factory that uses "this", something like that)
Perhaps is it a silly question, and I should do my "new" thing as I would if Guice wasn't around; but it is, so I'm trying to find the proper answer here.


Adrien.

Stephan Classen

unread,
Dec 19, 2014, 2:23:59 PM12/19/14
to google...@googlegroups.com
The thing you are looking for is called assisted injection.
https://github.com/google/guice/wiki/AssistedInject

But often when you need to pass runtime values to an object created with guice. The object is a mix between a data structure and a business object. Try to separate them and the assisted injection becomes unnecessarry.

Tim Boudreau

unread,
Dec 22, 2014, 9:10:12 PM12/22/14
to google...@googlegroups.com
What you have is a design problem.  If A needs B to exist, and B needs A to exist, then either

 - There is some other implicit object that provides data to both A and B, or
 - You really have one logical class, and your implementation is trying to pretend it's two

The most straightforward way to resolve this is don't use Guice to construct these.  I.e. A constructs a B and passes "this" to it and stores it as a field.  Done.

Or if you want to use Guice to construct it (and arguably a better design), have

@Inject
A (AandBData data) {...}
...
@Inject
B (AandBData data) {...}

-Tim

Stephan Classen

unread,
Dec 23, 2014, 2:39:13 AM12/23/14
to google...@googlegroups.com
If I read the example correctly. B does not need A. It just provides a method to retrieve a new instance of A.

So A and B should really be 2 separate classes.
Reply all
Reply to author
Forward
0 new messages