Java Reference
In-Depth Information
private static
Injector injector;
private static final
Log log =
Log.getInstance(GuiceInterceptor.
class
);
public void
init(Configuration config)
throws
Exception {
List<Class<?
extends
Module>> moduleClasses =
config.getBootstrapPropertyResolver()
.getClassPropertyList(MODULES, Module.
class
);
int
size = moduleClasses.size();
if
(size > 0) {
List<Module> modules =
new
ArrayList<Module>(size);
for
(Class<?
extends
Module> cls : moduleClasses) {
modules.add(cls.newInstance());
}
injector = Guice.createInjector(modules);
log.info("Created Guice injector with modules: ",
moduleClasses);
}
else
{
injector = Guice.createInjector();
}
}
public static
Injector getInjector() {
return
injector;
}
}
What this does is look for a list of
Module
classes configured in
web.xml
as an
init
parameter to the Stripes filter with the name
Guice.Modules
. If
there is no such parameter, then Stripes looks for classes that imple-
ment
Module
in the extension packages. That way, we have the option
of using an extension package or a parameter in
web.xml
, just like all
the other Stripes extensions.
Once we have the list of
Module
classes, it's simple to create instances
and use them to configure the Guice injector. We then use the injector
in the
intercept
( ) method that we wrote earlier to inject dependencies in
the action bean context and in the action bean. The injector is in a static
member to give easy access to it via
GuiceInterceptor.getInjector
( ), but
otherwise it wouldn't need to be since Stripes creates only one instance
of each interceptor.
Now that we have defined the Guice configuration and implemented the
Guice interceptor, we can use dependency injection on action beans
and the action bean context by tagging properties with Guice's
@Inject
annotation.
Search WWH ::
Custom Search