Created
July 7, 2014 19:14
-
-
Save gissuebot/1cd26ed07a1d99063606 to your computer and use it in GitHub Desktop.
Migrated attachment for Guice issue 805, comment 1
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.Guice; | |
import com.google.inject.Injector; | |
import com.google.inject.Key; | |
import com.google.inject.PrivateModule; | |
import javax.inject.Inject; | |
import java.lang.annotation.Annotation; | |
import static com.google.inject.name.Names.named; | |
import static java.lang.String.format; | |
public class RobotLegs | |
{ | |
private static final String leftName = "lefty"; | |
private static final String rightName = "righty"; | |
private static final Annotation leftAnnotation = named(leftName); | |
//private static final Annotation rightAnnotation = named(rightName); | |
private static final Annotation rightAnnotation = null; | |
private static Key<Leg> leftKey = Key.get(Leg.class, leftAnnotation); | |
//private static Key<Leg> rightKey = Key.get(Leg.class, rightAnnotation); | |
private static Key<Leg> rightKey = Key.get(Leg.class); | |
public static void main(String[] args) | |
{ | |
Injector injector = Guice.createInjector( | |
new AnnotatedLegModule(leftName, leftAnnotation), | |
new AnnotatedLegModule(rightName, rightAnnotation)); | |
Leg leftLeg = injector.getInstance(leftKey); | |
Leg rightLeg = injector.getInstance(rightKey); | |
System.out.println(format("left=%s foot=%s (%s)", leftLeg, leftLeg.foot, leftLeg.foot.side)); | |
System.out.println(format("right=%s foot=%s (%s)", rightLeg, rightLeg.foot, rightLeg.foot.side)); | |
} | |
public static class AnnotatedLegModule extends PrivateModule | |
{ | |
private final String side; | |
private final Annotation annotation; | |
public AnnotatedLegModule(String side, Annotation annotation) | |
{ | |
this.side = side; | |
this.annotation = annotation; | |
} | |
@Override | |
protected void configure() | |
{ | |
bind(Foot.class).toInstance(new Foot(side)); | |
if (annotation != null) { | |
bind(Leg.class).annotatedWith(annotation).to(Leg.class); | |
expose(Leg.class).annotatedWith(annotation); | |
} | |
else { | |
bind(Leg.class); | |
expose(Leg.class); | |
} | |
} | |
} | |
public static class Leg | |
{ | |
public final Foot foot; | |
@Inject | |
public Leg(Foot foot) | |
{ | |
this.foot = foot; | |
} | |
} | |
public static class Foot | |
{ | |
public final String side; | |
@Inject | |
public Foot(String side) | |
{ | |
this.side = side; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment