public
Created

Guice AssistedInject

  • Download Gist
GuiceExploratoryTest.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
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 {}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.