Created
February 3, 2015 14:05
-
-
Save avarabyeu/7b83ea4ac1040671ad0c to your computer and use it in GitHub Desktop.
Cache Guice Injector with TestNG (another way)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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