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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With