I don't think Guice had built-in support for companion, as a component-scan of the Spring structure. However, it is not difficult to simulate this feature in Guice.
You just need to write a helper module, like the following
import com.google.inject.AbstractModule; import org.reflections.Reflections; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public final class ComponentScanModule extends AbstractModule { private final String packageName; private final Set<Class<? extends Annotation>> bindingAnnotations; @SafeVarargs public ComponentScanModule(String packageName, final Class<? extends Annotation>... bindingAnnotations) { this.packageName = packageName; this.bindingAnnotations = new HashSet<>(Arrays.asList(bindingAnnotations)); } @Override public void configure() { Reflections packageReflections = new Reflections(packageName); bindingAnnotations.stream() .map(packageReflections::getTypesAnnotatedWith) .flatMap(Set::stream) .forEach(this::bind); } }
To have the component scan a package of type com.foo and com.foo for classes that carry @Singleton , use it as follows:
public class AppModule extends AbstractModule { public void configure() { install(new ComponentScanModule("com.foo", Singleton.class)); } }
source share