Guice是否支持方法注入(非二次注入)?

Sho*_*kie 3 java dependency-injection guice

根据我的理解,Guice支持注入:构造函数,Setter(由于某种原因它们称为方法注入),字段.

它还可以注入方法参数吗?例如:

void foo(InterfaceA a, InterfaceA a1){
    ...
}


interface InterfaceA{
    ...
}


class A implements InterfaceA{
    ....
}

class B implements InterfaceA{
    ....
}
Run Code Online (Sandbox Code Playgroud)

我希望能够绑定afoo输入Aa1B(可能需要注解,但是让忽略了第二).我希望这可以在调用时完成.

这似乎与正常用例(c'tor,fields,setters)不同,因为依赖注入将在调用时发生,而不是在对象创建上发生.

这可能吗?

Jef*_*ica 6

Vladimir的答案是正确的,但您可以使用字段注入和Providers更简洁地执行相同操作,并检查在注入器创建时是否满足依赖性,而不是注入注入器.此代码与他的相同,但修改为使用提供者:

Injector injector = Guice.createInjector(b -> {
    b.bind(InterfaceA.class).annotatedWith(Names.named("a")).to(A.class);
    b.bind(InterfaceA.class).annotatedWith(Names.named("a1")).to(B.class);
    b.bind(Invoke.class);
});

public class Invoke {
    // Constructor injection works too, of course. These fields could also be
    // made private, but this could make things difficult to test.
    @Inject @Named("a") Provider<InterfaceA> aProvider;
    @Inject @Named("a1") Provider<InterfaceA> a1Provider;

    public void invoke() {
        this.foo(aProvider.get(), a1Provider.get());
    }

    void foo(InterfaceA a, InterfaceA a1){
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)