guice忽略了提供者?

问题描述 投票:2回答:1

似乎Guice忽略了我模块的@Provider方法。

我有一个MyModule类,如下所示:

public class MyModule extends AbstractModule {

    protected void configure() {

        bindInterceptor(Matchers.any(), Matchers.annotatedWith(Timed.class), new GuiceEnabledLoggingInterceptor());
        bind(OneClass.class).to(OneClassImpl.class);

        // And more binding lines...

    }

    @Provides
    public AnotherClassInApi provideMyClass() {
        return AnotherClassInApi.getInstance();
    }

    // And more @Provides methods

}

主要方法是

public static void main(String[] args){
    ConfigHandler.getInstance().loadConfigWhenNotRunningInsideMicrocontainer();
    Injector INJECTOR = Guice.createInjector(new MyModule());
    // ...
}

在项目的其他部分,我有类AnotherClassInApi,这是一个非常标准的单例加一个方法:

public class AnotherClassInApi {

    private static final AnotherClassInApi INSTANCE = new AnotherClassInApi();

    private AnotherClassInApi() { }

    // ... more methods

    public static AnotherClassInApi getInstance() {
        return INSTANCE;
    }
}

好吧,我明白应该有效地将对AnotherClassInApi对象的任何请求绑定到getInstance()方法,但它不起作用。有趣的是,调试时从未达到@Provide方法中的断点,但是达到了configure方法中的一个。似乎guice忽略了我的提供者注释,我认为I'm following exactly what Guice guide says about @Provider,所以我已经卡住了。

我一直在谷歌上搜索,但找不到类似的东西。任何帮助都感激不尽。

谢谢!

annotations guice provider
1个回答
1
投票

Providers(和@Provides方法)的概念是,它们仅在实际需要时才被调用。因此,除非您真正使用Injector创建具有@Inject依赖关系的实例,否则不会忽略您的Provider,只是不使用(也不需要)。

您可以使用“injector.getAllBindings()”监视所有已配置的绑定。

java.util.Map,Binding> getAllBindings()

返回此注入器绑定的快照,包括显式和即时绑定。返回的映射是不可变的;它只包含调用getAllBindings()时存在的绑定。即时绑定仅在至少请求过一次时才会出现。后续调用可能会返回带有其他即时绑定的映射。如果存在,则返回的映射不包括从父注入器继承的绑定。

此方法是Guice SPI的一部分,旨在供工具和扩展使用。

© www.soinside.com 2019 - 2024. All rights reserved.