当构造函数有一个附加参数时关于guice构造注入的问题

Question on guice construction injection when there is an additional parameter to the constructor

我正在使用 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;
    }
}

这是因为 String class 提供并且 empty constructor。当 Guice 看到一个 String 被注入时,它会尝试找到 String 的绑定或者调用 String 的空构造函数 class.

来自Java的字符串class代码

/**
 * 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)