com.greenpepper.extensions.guice.GuiceSystemUnderDevelopment Maven / Gradle / Ivy
package com.greenpepper.extensions.guice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.greenpepper.reflect.DefaultFixture;
import com.greenpepper.reflect.Fixture;
import com.greenpepper.systemunderdevelopment.DefaultSystemUnderDevelopment;
/**
* GuiceSystemUnderDevelopment class.
*
* @author oaouattara
* @version $Id: $Id
*/
public class GuiceSystemUnderDevelopment
extends DefaultSystemUnderDevelopment
{
private Injector injector;
private List moduleNames = new ArrayList();
/**
* Constructor for GuiceSystemUnderDevelopment.
*/
public GuiceSystemUnderDevelopment()
{
}
/**
* Constructor for GuiceSystemUnderDevelopment.
*
* @param moduleNames a {@link java.lang.String} object.
*/
public GuiceSystemUnderDevelopment(String... moduleNames)
{
Collections.addAll(this.moduleNames, moduleNames);
}
/** {@inheritDoc} */
@Override
public Fixture getFixture(String name, String... params)
throws Throwable
{
lazilyInstantiateModulesAndInjector();
Fixture fixture;
if (params.length != 0)
{
// When params are used, we use the PlainOldSystemUnderDevelopment to instantiate the fixture
// these params are passed to the constructor
// Then we use Guice to inject members
fixture = super.getFixture(name, params);
injector.injectMembers(fixture.getTarget());
}
else
{
// Use Guice to instantiate
Class> klass = loadType(name).getUnderlyingClass();
Object target = injector.getInstance(klass);
fixture = new DefaultFixture(target);
}
return fixture;
}
private void lazilyInstantiateModulesAndInjector()
throws Exception
{
if (injector == null)
{
List modules = convertModuleNamesToModules();
injector = Guice.createInjector(modules);
}
}
private List convertModuleNamesToModules()
throws Exception
{
List modules = new ArrayList(moduleNames.size());
for (String moduleName : moduleNames)
{
Class> klass = loadType(moduleName).getUnderlyingClass();
modules.add((Module)klass.newInstance());
}
return modules;
}
/**
* addModules.
*
* @param moduleNames a {@link java.lang.String} object.
*/
public void addModules(String... moduleNames)
{
if (injector == null)
{
Collections.addAll(this.moduleNames, moduleNames);
}
else
{
throw new IllegalStateException("Cannot add module after a fixture has been instantiated");
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy