在guice模块中注入单例

发布于 2024-12-28 23:50:56 字数 834 浏览 4 评论 0原文

我用 guice 写了一些模块。这些效果很好。 我的模块中还有一些需要的单例或记录器,我想将它们注入到这些模块中。

例如,我有我的 JpaModule ,我需要我的配置。

ConfigurationModule:

@Singleton
public class ConfigurationModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Singleton.class);
  }
}

JpaModule:

public class JpaDaoModule extends AbstractModule {

  @Inject
  Configuration config;

  @Override
  protected void configure() {
    // ... Read config and do something
  }
}

调用 Guice:

Guice.createInjector(new ConfigurationModule(), new JpaDaoModule());

我怎样才能做到这一点?或者我如何以 guicy 的方式向 JpaModule 提供配置?

/亲切的问候

基督徒

I have written some modules with guice. These are working great.
I have also some singletons or a logger I need in my modules which I want to inject into these modules.

For example I have my JpaModule where I need my Configuration.

ConfigurationModule:

@Singleton
public class ConfigurationModule extends AbstractModule {

  @Override
  protected void configure() {
    bind(Configuration.class).toProvider(ConfigurationProvider.class).in(Singleton.class);
  }
}

JpaModule:

public class JpaDaoModule extends AbstractModule {

  @Inject
  Configuration config;

  @Override
  protected void configure() {
    // ... Read config and do something
  }
}

Call to Guice:

Guice.createInjector(new ConfigurationModule(), new JpaDaoModule());

How can I accomplish this? Or how can I provide the configuration to the JpaModule the guicy way?

/Kind regards

Christian

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沦落红尘 2025-01-04 23:50:56

这是不可能的。在 configure() 方法中,您可以设置绑定。您不能指望它们已经可用。此外,模块本身不符合注入条件。但是,您可以在提供者或 @Provides 方法中访问 Guice 管理的实例。

@Provides
@Named("myConfigItem")
String provideSomeConfigItem(Configuration config) {
    return config.get("myConfigItem");
}

This is not possible. In the configure() method you set up your bindings. You cannot expect them to be available already. Also, modules are not eligible for injection per se. You can, however, get access to Guice-managed instances in providers or @Provides methods.

@Provides
@Named("myConfigItem")
String provideSomeConfigItem(Configuration config) {
    return config.get("myConfigItem");
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文