Google Guice binding by annotation and / or package

I have 3 beans in one package which I would like to be eager singlons.

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 set them all up as strong singles without spelling the class name exactly using Google Guice?

I'm looking for something like labeling Bean1, Bean2, Bean3 with custom annotation or scan by package name.

+3


source to share


1 answer


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

comes from the Guava library that Guice 4 depends on. If you are using Guice 3, you probably need to add this dependency.

There may also be third party libraries containing annotation @EagerSingleton

, FWIW.

+3


source







All Articles