Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Oleksandr Horobets Avatar asked Jan 20 '26 16:01

Oleksandr Horobets


1 Answers

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.

like image 156
condit Avatar answered Jan 23 '26 06:01

condit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!