Google Guice 通过注解绑定 and/or 包

Google Guice bind by annotation and/or package

我在一个包中有 3 个豆子,我想成为渴望的单身人士。

public class Module1 implements Module {
    @Override
    public void configure(Binder binder) {
        binder.bind(Bean1.class).asEagerSingleton();
        binder.bind(Bean2.class).asEagerSingleton();
        binder.bind(Bean3.class).asEagerSingleton();
    }
}

如何在不使用 Google Guice 准确编写 class 名称的情况下将它们全部配置为热切的单例?

我正在寻找诸如通过一些自定义注释或通过包名称扫描来标记 Bean1、Bean2、Bean3 之类的东西。

我会这样做:

@Override
protected void configure() {
  try {
    for (ClassInfo classInfo: 
          ClassPath.from(getClass().getClassLoader()).getTopLevelClasses("my.package.name")) {
        bind(classInfo.load()).asEagerSingleton();
    }
  } catch (IOException e) { // Do something
  }
}

ClassPath 来自 Guice 4 所依赖的 Guava 库。如果您使用的是 Guice 3,您可能需要添加此依赖项。

可能还有包含 @EagerSingleton 注释 FWIW 的第 3 方库。