dependency-injectionguice

How to inject with Guice when there are two different constructors?


Total Guice noob here, have read a few articles and seen the intro video, that's about it.

Here's my simplified old code that I'm trying to "guicifiy". Can't quite figure out how to, since (as far as I understand), I can only @inject-annotate one of the two constructors? How can a calling class create the one or the other instance? Or will I have to refactor this somehow?

public class MyDialog extends JDialog {
    public MyDialog( JFrame parent, <other parameters...> ) {
        super( parent );
    }

    public MyDialog( JDialog parent, <other parameters...>) {
        super( parent );
    }
 }

Solution

  • You can only inject into the one ctor.

    Depending on how this class is being used, you could:

    How can a calling class create the one or the other instance?

    This suggests that the calling classes will want multiple instances of MyDialog? Then you need to use a hand-rolled factory (Assisted Inject can handle this for you if you only had one ctor). I don't know the details of what you are up to and I'm likely repeating what you already know but as a blanked statement I'd suggest also extracting an interface from MyDialog and have the factory return them. This way you can fake MyDialog in tests.