【问题标题】:Guice dependency issueGuice 依赖问题
【发布时间】:2018-05-10 15:54:08
【问题描述】:

我有一些带有 2 个注入命名实例的 DAO 类:

@Inject
@Named("Name1")
DSLContext dsl1;

@Inject
@Named("Name2")
DSLContext dsl2; 

一切正常。同时我想使用在它的构造函数中注入(未命名)DSLContext的不同类:

DSLContext dslContext;

@Inject
CommonsPlayerTokensDaoImpl(DSLContext dslContext) {
    this.dslContext = dslContext;
}

我想在这里使用我现有的上下文之一。当然,在这种情况下,Guice 无法自动解决依赖关系。我该怎么做?

谢谢, 埃德

【问题讨论】:

标签: java guice


【解决方案1】:

您可以将@Named注解与构造函数的参数一起使用:
@Inject CommonsPlayerTokensDaoImpl(@Named("Name1") DSLContext dslContext) {

【讨论】:

  • 是的,我可以而且我做到了...但是是否可以在不更改具有构造函数的类的情况下注入特定实例?
  • 下一个想法是在 Guice 模块中使用带有 @Provides 注释的方法:@Provides public CommonsPlayerTokensDaoImpl provideCommonsPlayerTokensDaoImpl(@Named("Name2") DSLContext dslContext) { return new CommonsPlayerTokensDaoImpl(dslContext); }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多