Skip to content

Instantly share code, notes, and snippets.

@avarabyeu
Last active August 29, 2015 14:14
Show Gist options
  • Save avarabyeu/e2a49e5d67008695f361 to your computer and use it in GitHub Desktop.
Save avarabyeu/e2a49e5d67008695f361 to your computer and use it in GitHub Desktop.
Cache Guice Injector with TestNG (best way)
/**
* @author Andrei Varabyeu
*/
public abstract class CachedModuleFactory<T extends Module> implements IModuleFactory {
private static final Cache<Class<? extends Module>, Injector> CACHE =
CacheBuilder.<Class<? extends Module>, Injector>newBuilder().build();
private final Callable<Injector> INJECTOR_LOADER = new Callable<Injector>() {
@Override
public Injector call() throws Exception {
return Guice.createInjector(createParentModule());
}
};
abstract protected T createParentModule();
abstract protected Class<T> getParentModuleType();
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)) {
boolean cached = testClass.getAnnotation(UseParentInjector.class).cached();
Injector injector = cached ? getCached(getParentModuleType()) : Guice.createInjector(createParentModule());
context.addInjector(Collections.singletonList(childModule),
injector.createChildInjector(childModule));
}
return childModule;
}
private Injector getCached(final Class<T> moduleType) {
try {
return CACHE.get(moduleType, INJECTOR_LOADER);
} catch (ExecutionException e) {
throw new UncheckedExecutionException(e.getCause());
}
}
}
/**
* @author Andrei Varabyeu
*/
@Retention(RUNTIME)
@Target({ElementType.TYPE})
public @interface UseParentInjector {
boolean cached() default true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment