Skip to content

Instantly share code, notes, and snippets.

@Atsumi3
Created June 14, 2018 09:40
Show Gist options
  • Save Atsumi3/50f29a09408f4a98683f9f88289365fb to your computer and use it in GitHub Desktop.
Save Atsumi3/50f29a09408f4a98683f9f88289365fb to your computer and use it in GitHub Desktop.
Simple Dagger2 (Pure Java)
import dagger.Component;
import dagger.Module;
import dagger.Provides;
import javax.inject.Inject;
public class Main {
public static void main(String[] args) {
AnimalCry animalCry = new AnimalCry();
animalCry.cry();
}
static class AnimalCry {
@Inject
Animal animal;
AnimalCry() {
AnimalComponent component = DaggerMain_AnimalComponent.builder().build();
component.inject(this);
}
void cry() {
System.out.println(animal.cry());
}
}
interface Animal {
String cry();
}
static class Cat implements Animal {
@Override
public String cry() {
return "nya";
}
}
// Module
@Module
static class AnimalModule {
@Provides
static Animal provideAnimal() {
return new Cat();
}
}
// Component
@Component(modules = AnimalModule.class)
interface AnimalComponent {
void inject(AnimalCry animalCry);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment