简体   繁体   中英

Google Guice bind by annotation and/or package

I have 3 beans in one package that I would like to be eager singletons.

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();
    }
}

How can I configure them all as eager singletons without exact writing class name using Google Guice?

I'm looking for something like marking Bean1, Bean2, Bean3 by some custom annotation or scanning by package name.

I would do something like this:

@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 is coming from the Guava library which Guice 4 depends. If you're using Guice 3 you will probably need to add this dependency.

There may also be 3rd party libraries that include an @EagerSingleton annotation, FWIW.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM