Skip to content

Instantly share code, notes, and snippets.

Created January 7, 2013 22:23
Show Gist options
  • Save anonymous/4479085 to your computer and use it in GitHub Desktop.
Save anonymous/4479085 to your computer and use it in GitHub Desktop.
Simple of example of how to use injection with objects that require things which cannot always be injected.
public class Consumer {
@Inject ExampleClass.Factory exampleClassFactory;
public void fireZeMissles() {
ExampleClass ex = exampleClassFactory.createForUser(42);
ex.doThings();
}
}
public class ExampleClass {
private final int userId;
private final FooBar fooBar;
private final Gizmo gizmo;
private ExampleClass(int userId, FooBar fooBar, Gizmo gizmo) {
this.userId = userId;
this.fooBar = fooBar;
this.gizmo = gizmo;
}
public void doThings() {
// ...
}
public static class Factory {
private final FooBar fooBar;
private final Gizmo gizmo;
@Inject public Factory(FooBar fooBar, Gizmo gizmo) {
this.fooBar = fooBar;
this.gizmo = gizmo;
}
public ExampleClass createForUser(int userId) {
return new ExampleClass(userId, fooBar, gizmo);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment