【问题标题】:Java Guice Named Bindings with Objects provided from other modulesJava Guice 命名绑定与其他模块提供的对象
【发布时间】:2021-04-15 20:14:52
【问题描述】:

这是我当前的设置

类文件

public class ToyAdapter {

private final ToyClient toyClient;
private final Retryer retryer;

    @Inject
    public APIAdapter(final ToyClient toyClient,
                        @Named("toyRetryer") final Retryer retryer) {
        this.toyClient = toyClient;
        this.retryer = retryer;
    }

Guice 文件
我有几个 guice 模块,但是这个属于上面的类

public class ToyModule extends AbstractModule {

    @Override
    protected void configure() {

        bind(ToyAdapter.class).in(Singleton.class);
        bind(Retryer.class).annotatedWith(Names.named("toyRetryer")).toInstance(getToyRetryer());
    }

    @Provides
    @Singleton
    public ToyClient getToyClient(...){
       ...
    }

    private Retryer getToyRetryer() {#Takes no arguments
        return RetryerBuilder...build();
    }
}

到目前为止,这很好用!但是,现在我的重试器需要另一个模块中提供的 LogPublisher 对象。

我在努力

public class ToyModule extends AbstractModule {

    LogPublisher logPublisher;

    @Override
    protected void configure() {
        requestInjection(logPublisher);
        bind(ToyAdapter.class).in(Singleton.class);
        bind(Retryer.class).annotatedWith(Names.named("toyRetryer")).toInstance(getToyRetryer());
    }
    
    private Retryer getToyRetryer() {
        return RetryerBuilder.withLogPublisher(logPublisher).build();
    }
}

LogPublisher 是在另一个 guice 模块中提供的,该模块有很多其他依赖于 LogPublisher 的对象,所以我宁愿不只是将所有内容合并到一个巨大的 guice 模块中。

@Provides
@Singleton
public LogPublisher getLogPublisher() {...}

这是正确的方法吗?我收到 Java findBugs 错误提示 unwritten field 所以我认为我做错了。

【问题讨论】:

    标签: java dependency-injection guice


    【解决方案1】:

    借助 @Provides/@Named 注释声明您的 Retryer

        @Provides
        @Singleton
        @Named("toyRetryer")
        public Retryer getToyRetryer(LogPublisher logPublisher) {
            return RetryerBuilder.withLogPublisher(logPublisher).build();
        }
    

    【讨论】:

    • 谢谢,我可以使用 javax.inject.Named 还是必须使用 guice 的?
    • 应该没问题,但我会坚持javax.inject
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2011-09-13
    相关资源
    最近更新 更多