Created
September 28, 2012 22:00
-
-
Save noel-yap/3802302 to your computer and use it in GitHub Desktop.
Guice AssistedInject
This file contains 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
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