-
Notifications
You must be signed in to change notification settings - Fork 1
InspectingModules
Inspecting what makes up a Module & examining Bindings
Guice provides a rich service provider interface (SPI) for all the elements that make up a module. You can use this SPI to learn what bindings are in a module and even rewrite some of those bindings. Modules.override is written entirely using this SPI.
Examining Elements
The Elements class provides access to each Element within a Module. You can use this class to get individual elements from a module and take action upon them. Each Element has an acceptVisitor method that takes an ElementVisitor. You can use DefaultElementVisitor to simplify writing a visitor.
void warnAboutStaticInjections(Module... modules) {
for(Element element : Elements.getElements(modules)) {
element.acceptVisitor(new DefaultElementVisitor<Void>() {
@Override public void visit(StaticInjectionRequest request) {
System.out.println("You shouldn't be using static injection at: " + request.getSource());
}
});
}
}
You can use the SPI to do anything from stripping out elements to rewriting elements to adding new elements. When you've finished wiring your elements, you can turn them back into a module.
Module stripStaticInjections(Module... modules) {
final List<Element> noStatics = Lists.newArrayList();
for(Element element : Elements.getElements(modules)) {
element.acceptVisitor(new DefaultElementVisitor<Void>() {
@Override public void visit(StaticInjectionRequest request) {
// override to not call visitOther
}
@Override public void visitOther(Element element) {
noStatics.add(element);
}
});
}
return Elements.getModule(noStatics);
}
The most common Element is a Binding. Bindings have more configuration than other elements and can be inspected in more ways. You can visit a binding's scope using Binding.acceptScopingVisitor), or figure out what kind of binding it is using Binding.acceptTargetVisitor. Each of these methods have their own default visitors (DefaultBindingScopingVisitor and DefaultBindingTargetVisitor, respectively) to make visiting easier.
Bindings can either be "Module bindings" or "Injector bindings". Injector bindings are bindings retrieved from an injector (see the Injector javadoc). Module bindings are bindings retrieved using the Elements SPI. The Binding javadoc explains the difference between these in more detail.
Guice 3.0 adds the ability for extensions to write their own SPI. See ExtensionSPI for details.
- User's Guide
- Best Practices
- Frequently Asked Questions
- Integration
- Extensions
- Internals
- Releases
- Community