1

I am new to Guice and searched on google for this problem but couldn't find satisfactory answer.

public class X {
    private Y y;

    public X() {
        y = new Y("abc", "xyz");
    }
}

public class Y {
    private String str1;
    private String str2;

    public Y(String str1, String str2) {
        this.str1 = str1;
        this.str2 = str2;
    }
}

Now, I want to inject Y into constructor of class X.

I did find AssistedInject but isn't it for constructor which has parameters some of which are provided by Guice and some of them are provided by caller.

Here, in this case, all the parameters to the constructor are provided by caller only.

How can I do that?

2 Answers 2

3

You can use a binding annotation (or the builtin @Named) for this, see the 1st Q in the Guice FAQ

This gives you a way to disambiguate 2 identical types. For example

// in the module
bind(String.class).annotatedWith(Names.named("logical.env.id")).toInstance(System.getProperty("logical.env.id", "UK"));

// in the class
@Inject
public Foo(Bar barInstance, @Named("logical.env.id") String logicalEnvId) {
}
Sign up to request clarification or add additional context in comments.

Comments

1

I did find AssistedInject but isn't it for constructor which has parameters some of which are provided by Guice and some of them are provided by caller.

Correct.

Here, in this case, all the parameters to the constructor are provided by caller only.

How can I do that?

Just do it the way you did: with new Y(...) in X constructor.

Why do you want to use Guice in this situation?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.