Skip to content

Instantly share code, notes, and snippets.

@avarabyeu
Last active August 29, 2015 14:14
Show Gist options
  • Save avarabyeu/d7651146d87aaabafa53 to your computer and use it in GitHub Desktop.
Save avarabyeu/d7651146d87aaabafa53 to your computer and use it in GitHub Desktop.
Cache Guice Injector with TestNG
/**
* @author Andrei Varabyeu
*/
public abstract class CachedModuleFactory implements IModuleFactory {
private static volatile Injector parentInjector;
private static final Object LOCK = new Object();
private Injector getParentInjector() {
/* make sure we create injector only once */
if (null == parentInjector) {
/* locks this area from concurrent calls for ALL instances */
synchronized (LOCK) {
if (null == parentInjector) {
parentInjector = Guice.createInjector(createParentModule());
}
}
}
return parentInjector;
}
abstract protected Module createParentModule();
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(UseCachedInjector.class)) {
context.addInjector(Collections.singletonList(childModule),
getParentInjector().createChildInjector(childModule));
}
return childModule;
}
}
/**
* @author Andrei Varabyeu
*/
@Retention(RUNTIME)
@Target({ElementType.TYPE})
public @interface UseCachedInjector {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment