Skip to content

Instantly share code, notes, and snippets.

@noel-yap
Created September 28, 2012 22:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noel-yap/3802302 to your computer and use it in GitHub Desktop.
Save noel-yap/3802302 to your computer and use it in GitHub Desktop.
Guice AssistedInject
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.FactoryModuleBuilder;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class GuiceExploratoryTest {
private static final String VALUE_ASSISTED_NAME = "value";
@Test
public void instantiateFactory() {
final Injector injector = Guice.createInjector(new Module());
final AoeuFactory aoeuFactory = injector.getInstance(AoeuFactory.class);
final Aoeu aoeu = aoeuFactory.create("aoeu");
assertThat(aoeu.getValueKnownByTheCreatorOfAoeuClass(), is("aoeu"));
}
public static class Module extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder()
.implement(Aoeu.class, Aoeu.class)
.build(AoeuFactory.class));
}
}
public static class Aoeu {
private final DependencyInjectedTheUsualWay dependencyInjectedTheUsualWay;
private final String valueKnownByTheCreatorOfAoeuClass;
@Inject
public Aoeu(
final DependencyInjectedTheUsualWay dependencyInjectedTheUsualWay,
@Assisted(VALUE_ASSISTED_NAME) final String valueKnownByTheCreatorOfAoeuClass) {
this.dependencyInjectedTheUsualWay = dependencyInjectedTheUsualWay;
this.valueKnownByTheCreatorOfAoeuClass = valueKnownByTheCreatorOfAoeuClass;
}
public String getValueKnownByTheCreatorOfAoeuClass() {
return valueKnownByTheCreatorOfAoeuClass;
}
}
public static interface AoeuFactory {
public Aoeu create(
@Assisted(VALUE_ASSISTED_NAME) final String string);
}
private static class DependencyInjectedTheUsualWay {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment