Last active
August 29, 2015 14:14
-
-
Save avarabyeu/d7651146d87aaabafa53 to your computer and use it in GitHub Desktop.
Cache Guice Injector with TestNG
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 { | |
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; | |
} | |
} |
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 UseCachedInjector { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment