Skip to content

Instantly share code, notes, and snippets.

@avarabyeu
Created February 3, 2015 14:05
Show Gist options
  • Save avarabyeu/7b83ea4ac1040671ad0c to your computer and use it in GitHub Desktop.
Save avarabyeu/7b83ea4ac1040671ad0c to your computer and use it in GitHub Desktop.
Cache Guice Injector with TestNG (another way)
/**
* @author Andrei Varabyeu
*/
public abstract class CachedModuleFactory implements IModuleFactory {
/* delegate creating and holding of parent injector to subclass */
abstract protected Injector getParentInjector();
abstract protected Module createTestModule(ITestContext context, Class<?> testClass);
@Override
final public Module createModule(ITestContext context, Class<?> testClass) {
Module childModule = createTestModule(context, testClass);
if (testClass.isAnnotationPresent(UseParentInjector.class)) {
context.addInjector(Collections.singletonList(childModule),
getParentInjector().createChildInjector(childModule));
}
return childModule;
}
}
public static class ModuleFactory extends CachedModuleFactory {
/* Singleton with double-checked locking and lazy initialization using Guava */
private static final Supplier<Injector> PARENT_INJECTOR = Suppliers.memoize(new Supplier<Injector>() {
@Override
public Injector get() {
//create your parent injector here
return null;
}
});
@Override
protected Injector getParentInjector() {
return PARENT_INJECTOR.get();
}
@Override
protected Module createTestModule(ITestContext context, Class<?> testClass) {
return new ChildModule();
}
}
/**
* @author Andrei Varabyeu
*/
@Retention(RUNTIME)
@Target({ElementType.TYPE})
public @interface UseParentInjector {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment