Reputation: 1375
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.
Upvotes: 3
Views: 1423
Reputation: 10972
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.
Upvotes: 4