Вопрос о внедрении конструкции guice, когда в конструкторе есть дополнительный параметр - PullRequest
0 голосов
/ 20 февраля 2020

Я использую guice-4.1.0. Вывод следующего кода: in b, host:. Я ожидал ошибки. Потому что нигде host явно не было дано конструктору. Есть идеи?

package com.mycompany.app;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;

public class App
{
    public static void main( String[] args )
    {
        Injector injector = Guice.createInjector(new AppModule());
        Client client = injector.getInstance(Client.class);
        client.foo();
    }
}

class AppModule extends AbstractModule {
    @Override
    protected void configure() {  
        bind(B.class).to(BImpl.class);
    }
}

class Client {
    private B b;

    @Inject
    public Client(B b) {
        this.b = b;
    }

    public void foo() {
        System.out.println(b.foo());
    }
}

interface B {
    String foo();
}

class BImpl implements B {
    private String host;

    @Inject
    public BImpl(String host) {
        this.host = host;
    }

    public String foo() {
        return "in b, host: " + host;
    }
}

1 Ответ

1 голос
/ 20 февраля 2020

Это происходит потому, что класс String предоставляет и empty constructor. Когда Guice видит, что String вводится, он пытается найти привязку для String или вызывает пустой конструктор класса String.

Из Java кода класса String

/**
 * Initializes a newly created {@code String} object so that it represents
 * an empty character sequence.  Note that use of this constructor is
 * unnecessary since Strings are immutable.
 */
public String() {
    this.value = "".value;
}

Как видите, оно устанавливает значение "". По этой причине вы видите, что пустая строка печатается на выходе.

Попробуйте то же самое, например, с Integer, и вы получите

Could not find a suitable constructor in java.lang.Integer. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private. at java.lang.Integer.class(Integer.java:52)
...